GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — data.table/src/fread.c at master · 0xtch/data.table Expand file tree/ Copy pathfread.cMore file actions 3033 lines (2829 loc) · 140 KB / Copy pathfread.cFile metadata and controls3033 lines (2829 loc) · 140 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #include "fread.h" // include fread.h should happen before include time.h to avoid compilation warning on windows about re-defining __USE_MINGW_ANSI_STDIO, PR#5395. #if defined(CLOCK_REALTIME) && !defined(DISABLE_CLOCK_REALTIME) #define HAS_CLOCK_REALTIME #endif #ifdef HAS_CLOCK_REALTIME #include <time.h> // clock_gettime for wallclock() #else #include <sys/time.h> // gettimeofday for wallclock() #endif #ifdef WIN32 // means WIN64, too, oddly #include <windows.h> #else #include <sys/mman.h> // mmap #include <sys/stat.h> // fstat for filesize #include <fcntl.h> // open #include <unistd.h> // close #include <ctype.h> // isspace #include <errno.h> // errno #include <string.h> // strerror #include <stdarg.h> // va_list, va_start #include <stdio.h> // snprintf #include <math.h> // ceil, sqrt, isfinite #endif #include <stdbool.h> #include "freadLookups.h" // Private globals to save passing all of them through to highly iterated field processors static const char *sof, *eof; static char sep; static char whiteChar; // what to consider as whitespace to skip: ' ', '\t' or 0 means both (when sep!=' ' && sep!='\t') static char quote, dec; static char commentChar; static int linesForDecDot; // when dec='auto', track the balance of fields in favor of dec='.' vs dec=',', ties go to '.' static bool eol_one_r; // only true very rarely for \r-only files enum quote_rule_t { // Fields may be quoted, any quote inside the field is doubled.This is // the CSV standard. For example: <<...,"hello ""world""",...>> QUOTE_RULE_EMBEDDED_QUOTES_DOUBLED, // Fields may be quoted, any quotes inside are escaped with a backslash. // For example: <<...,"hello \"world\"",...>> QUOTE_RULE_EMBEDDED_QUOTES_ESCAPED, // Fields may be quoted, but any quotes inside will appear verbatim and // not escaped in any way. It is not always possible to parse the file // unambiguously, but we give it a try anyways. A quote will be presumed // to mark the end of the field iff it is followed by the field separator. // Under this rule eol characters cannot appear inside the field. // For example: <<...,"hello "world"",...>> QUOTE_RULE_EMBEDDED_QUOTES_NOT_ESCAPED, // Fields are not quoted at all. Any quote characters appearing anywhere // inside the field will be treated as any other regular characters. // Example: <<...,hello "world",...>> QUOTE_RULE_IGNORE_QUOTES, QUOTE_RULE_COUNT }; static enum quote_rule_t quoteRule; static const char* const* NAstrings; static bool any_number_like_NAstrings = false; static bool blank_is_a_NAstring = false; static bool stripWhite = true; // only applies to character columns; numeric fields always stripped static bool skipEmptyLines = false; static int fill = 0; static int *dropFill = NULL; static double NA_FLOAT64; // takes fread.h:NA_FLOAT64_VALUE // Private globals so they can be cleaned up both on error and on successful return static void *mmp = NULL; static void *mmp_copy = NULL; static size_t fileSize; static int8_t *type = NULL, *tmpType = NULL, *size = NULL; static lenOff *colNames = NULL; static freadMainArgs args = { 0 }; // global for use by DTPRINT; static implies ={ 0 } but include the ={ 0 } anyway just in case for valgrind #4639 #ifdef __EMSCRIPTEN__ // Under Wasm we must keep the fd open until we're done with the mmap, due to an Emscripten bug (#5969). // TODO(emscripten-core/emscripten#20459): revert this static int mmp_fd = -1; #endif // See header for more explanation. const char typeName[NUMTYPE][10] = { "drop", "bool8", "bool8", "bool8", "bool8", "bool8", "bool8", "int32", "int64", "float64", "float64", "float64", "int32", "float64", "string" }; int8_t typeSize[NUMTYPE] = { 0, 1, 1, 1, 1, 1, 1, 4, 8, 8, 8, 8, 4, 8, 8 }; // In AIX, NAN and INFINITY don't qualify as constant literals. Refer: PR #3043 // So we assign them through below init_const_literals function. static double NAND; static double INFD; // NAN and INFINITY constants are float, so cast to double once up front. static void init_const_literals(void) { NAND = (double)NAN; INFD = (double)INFINITY; } typedef struct FieldParseContext { // Pointer to the current parsing location const char **ch; // Parse target buffers, indexed by size. A parser that reads values of byte // size `sz` will attempt to write that value into `targets[sz]`. Thus, // generally this is an array with elements 0, 1, 4, and 8 defined, while all // other pointers are NULL. void **targets; // String "anchor" for `Field()` parser -- the difference `ch - anchor` will // be written out as the string offset. const char *anchor; } FieldParseContext; // Forward declarations static void Field(FieldParseContext *ctx); #define ASSERT(cond, msg, ...) if (!(cond)) INTERNAL_STOP(msg, __VA_ARGS__) // # nocov #define AS_DIGIT(x) (uint_fast8_t)(x - '0') #define IS_DIGIT(x) (AS_DIGIT(x) < 10) // Readability helpers for the ad-hoc type bumping system: flip e.g. // type '1' to '-1' to mark out-of-sample type bumps, i.e., cases // where the type inferred during auto-detection (which only uses // a sample of rows) winds up being incorrect when considering the // full input. #define IGNORE_BUMP(x) abs(x) #define TOGGLE_BUMP(x) (-x) #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L # define typeof(x) __typeof__(x) // nonstandard but widely supported extension #endif #define OFFSET_POINTER(x, offset) ((typeof(x))((char*)x + (offset))) //================================================================================================= // // Utility functions // //================================================================================================= /** * Drops `const` qualifier from a `const char*` variable, equivalent of * `const_cast<char*>` in C++. */ static char* const_cast(const char *ptr) { union { const char *a; char *b; } tmp = { ptr }; return tmp.b; } /** * Free any resources / memory buffers allocated by the fread() function, and * bring all global variables to a "clean slate". This function should always be * executed when fread() exits, either successfully or not. But if it doesn't * for some reason (e.g. unexpected error/bug) then it is called again on starting * with verbose message if it needed to clean anything up. */ bool freadCleanup(void) { const bool neededCleanup = (type || tmpType || size || colNames || mmp || mmp_copy); free(type); type = NULL; free(tmpType); tmpType = NULL; free(size); size = NULL; free(colNames); colNames = NULL; free(dropFill); dropFill = NULL; if (mmp != NULL) { // Important to unmap as OS keeps internal reference open on file. Process is not exiting as // we're a .so/.dll here. If this was a process exiting we wouldn't need to unmap. // // Note that if there was an error unmapping the view of file, then we should not attempt // to call STOP() for 2 reasons: 1) freadCleanup() may have itself been called from STOP(), // and we would not want to overwrite the original error message; and 2) STOP() function // may call freadCleanup(), thus resulting in an infinite loop. #ifdef WIN32 if (!UnmapViewOfFile(mmp)) // GetLastError is a 'DWORD', not 'int', hence '%lu' DTPRINT(_("System error %lu unmapping view of file\n"), GetLastError()); // # nocov #else if (munmap(mmp, fileSize)) DTPRINT(_("System errno %d unmapping file: %s\n"), errno, strerror(errno)); // # nocov #ifdef __EMSCRIPTEN__ close(mmp_fd); mmp_fd = -1; #endif #endif mmp = NULL; } free(mmp_copy); mmp_copy = NULL; fileSize = 0; sep = whiteChar = quote = dec = commentChar = '\0'; quoteRule = -1; any_number_like_NAstrings = false; blank_is_a_NAstring = false; stripWhite = true; skipEmptyLines = false; eol_one_r = false; fill = 0; // following are borrowed references: do not free sof = eof = NULL; NAstrings = NULL; return neededCleanup; } #define CEIL(x) ((uint64_t)(double)ceil(x)) static inline uint64_t umax(uint64_t a, uint64_t b) { return a > b ? a : b; } static inline uint64_t umin(uint64_t a, uint64_t b) { return a < b ? a : b; } static inline int64_t imin( int64_t a, int64_t b) { return a < b ? a : b; } static inline int iminInt( int a, int b) { return a < b ? a : b; } /** Return value of `x` clamped to the range [upper, lower] */ static inline int64_t clamp_i64t(int64_t x, int64_t lower, int64_t upper) { return x < lower ? lower : x > upper ? upper : x; } /** * Helper for error and warning messages to extract an input line starting at * `*ch` and until an end of line, but no longer than `limit` characters. * This function returns the string copied into a caller-allocated buffer (typically on the stack). * Parameter `limit` should not exceed STRLIM_BUF_SIZE-1 (500). * The data might contain % characters. Therefore, careful to ensure that if the msg * is constructed manually (using say snprintf) that warning(), stop() * and Rprintf() are all called as warning(_("%s"), msg) and not warning(msg). */ #define STRLIM_BUF_SIZE 501 static const char* strlim(const char *ch, char buf[static STRLIM_BUF_SIZE], size_t limit) { if (limit >= STRLIM_BUF_SIZE) limit = STRLIM_BUF_SIZE-1; char *ch2 = buf; for (size_t width = 0; (*ch > '\r' || (*ch != '\0' && *ch != '\r' && *ch != '\n')) && width < limit; width++) { *ch2++ = *ch++; } *ch2 = '\0'; return buf; } static const char *typeLetter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static char *typesAsString(int ncol) { const int nLetters = strlen(typeLetter); if (NUMTYPE > nLetters) INTERNAL_STOP("NUMTYPE(%d) > nLetters(%d)", NUMTYPE, nLetters); // # nocov static char str[101]; int i = 0; if (ncol <= 100) { for (; i < ncol; i++) str[i] = typeLetter[IGNORE_BUMP(type[i])]; } else { for (; i < 80; i++) str[i] = typeLetter[IGNORE_BUMP(type[i])]; str[i++] = '.'; str[i++] = '.'; str[i++] = '.'; for (int j = ncol - 10; j < ncol; j++) str[i++] = typeLetter[IGNORE_BUMP(type[j])]; } str[i] = '\0'; return str; } static inline void skip_white(const char **pch) { // skip space so long as sep isn't space and skip tab so long as sep isn't tab // always skip any \0 (NUL) that occur before end of file, #3400 const char *ch = *pch; if (whiteChar == 0) { // whiteChar==0 means skip both ' ' and '\t'; sep is neither ' ' nor '\t'. while (*ch == ' ' || *ch == '\t' || (*ch == '\0' && ch < eof)) ch++; } else { while (*ch == whiteChar || (*ch == '\0' && ch < eof)) ch++; // sep is ' ' or '\t' so just skip the other one. } *pch = ch; } /** * Advance `ch` past spaces/NULs until we hit a comment marker or the first * non-whitespace character. Leaves `ch` unchanged if already on content. */ static inline const char *skip_to_comment_or_nonwhite(const char *ch) { while (ch < eof && *ch == '\0') ++ch; if (!stripWhite) return ch; while (ch < eof && (*ch == ' ' || *ch == '\t')) { if (*ch == commentChar) break; ++ch; } return ch; } /** * eol() accepts a position and, if any of the following line endings, moves to the end of that sequence * and returns true. Repeated \\r around \n are considered one. At most one \\n will be moved over, though. * 1. \\n Unix * 2. \\r\\n Windows * 3. \\r\\r\\n R's download.file() in text mode doubling up \\r * 4. \\r Old MacOS 9 format discontinued in 2002 but then #2347 was raised straight away when I tried not to support it, #2371 * 5. \\n\\r Acorn BBC (!) and RISC OS according to Wikipedia. * 6. \\r\\r\\r Not supported. So that blank lines in single column files generate NA ok, #2542. */ static inline bool eol(const char **pch) { const char *ch = *pch; // we call eol() when we expect to be on an eol(), so optimize as if we are on an eol while (*ch == '\r') ch++; // commonly happens once on Windows for type 2 if (*ch == '\n') { // 1,2,3 and 5 (one \n with any number of \r before and/or after) // most common branch as we only call eol() when we expect to be on eol while (ch[1] == '\r') ch++; // type 5. Could drop but we're only tepid here so keep for completeness and full generality. *pch = ch; return true; } return eol_one_r && **pch == '\r'; } /** * Walk to the newline sequence terminating the current line and return the pointer to its final * character (or `eof` if none exists). */ static inline const char *skip_to_eol(const char *ch, const char *eof) { while (ch < eof && *ch != '\n' && *ch != '\r') ch++; if (ch < eof) { const char *tmp = ch; if (eol(&tmp)) ch = tmp; } return ch; } /** * Skip past the current line (including its newline sequence) and return the first character of the * next line, or `eof` if none exists. */ static inline const char *skip_to_nextline(const char *ch, const char *eof) { const char *lineEnd = skip_to_eol(ch, eof); if (lineEnd < eof) lineEnd++; return lineEnd; } /** * Return True iff `ch` is a valid field terminator character: either a field * separator or a newline. */ static inline bool end_of_field(const char *ch) { // \r is 13, \n is 10, and \0 is 0. The second part is optimized based on the // fact that the characters in the ASCII range 0..13 are very rare, so a // single check `ch<=13` is almost equivalent to checking whether `ch` is one // of \r, \n, \0. We cast to unsigned first because `char` type is signed by // default, and therefore characters in the range 0x80-0xFF are negative. // We use eol() because that looks at eol_one_r inside it w.r.t. \r // \0 (maybe more than one) before eof are part of field and do not end it; eol() returns false for \0 but the ch==eof will return true for the \0 at eof. // Comment characters terminate a field immediately and take precedence over separators. if (*ch == sep) return true; if (ch == eof) return true; if ((uint8_t)*ch <= 13 && eol(&ch)) return true; if (!commentChar) return false; return *ch == commentChar; } static inline const char *end_NA_string(const char *start) { // start should be at the beginning of any potential NA string, after leading whitespace skipped by caller const char* const* nastr = NAstrings; const char *mostConsumed = start; // tests 1550* includes both 'na' and 'nan' in nastrings. Don't stop after 'na' if 'nan' can be consumed too. if (nastr) while (*nastr) { const char *ch1 = start; const char *ch2 = *nastr; while (*ch1 == *ch2 && *ch2 != '\0') { ch1++; ch2++; } if (*ch2 == '\0' && ch1 > mostConsumed) mostConsumed = ch1; nastr++; } return mostConsumed; } /** * Compute the number of fields on the current line (taking into account the * global `sep` and `quoteRule`), and move the parsing location to the * beginning of the next line. * Returns the number of fields on the current line, or -1 if the line cannot * be parsed using current settings. * This does not need to be particularly efficient; it's just used for format detection. */ static inline int countfields(const char **pch) { static lenOff trash; // see comment on other trash declarations static void *targets[9]; targets[8] = (void*) &trash; const char *ch = *pch; for (;;) { if (ch >= eof) { *pch = ch; return 0; } if (sep == ' ') while (*ch == ' ') ch++; // multiple sep==' ' at the start does not mean sep skip_white(&ch); if (commentChar && *ch == commentChar) { const char *next = skip_to_nextline(ch, eof); if (next < eof) { ch = next; continue; // rescan next line } *pch = next; return 0; } break; } if (eol(&ch) || ch == eof) { *pch = ch + 1; return 0; } int ncol = 1; FieldParseContext ctx = { .ch = &ch, .targets = targets, .anchor = NULL, }; while (ch < eof) { Field(&ctx); if (commentChar && *ch == commentChar) { ch = skip_to_nextline(ch, eof); *pch = ch; return ncol; } // Field() leaves *ch resting on sep, \r, \n or *eof=='\0' if (sep == ' ' && *ch == sep) { while (ch[1] == ' ') ch++; if (ch[1] == '\r' || ch[1] == '\n' || (ch[1] == '\0' && ch + 1 == eof)) { // reached end of line. Ignore padding spaces at the end of line. ch++; // Move onto end of line character } } if (*ch == sep) { ch++; ncol++; continue; } if (eol(&ch)) { *pch = ch + 1; return ncol; } if (ch != eof) return -1; // -1 means this line not valid for this sep and quote rule break; } *pch = ch; return ncol; } static inline const char *nextGoodLine(const char *ch, int ncol) { // We may have landed inside a quoted field containing embedded sep and/or embedded \n. // Find next \n and see if ncol fields are found there. If not, test the \n after that, etc. // If this doesn't return the true line start, no matter. The previous thread will run-on and // resolve it. A good guess is all we need here. Being wrong will just be a bit slower. // If there are no embedded newlines, all newlines are true, and this guess will never be wrong. ch = skip_to_nextline(ch, eof); if (ch == eof) return eof; const char *simpleNext = ch; // simply the first newline after the jump // if a better one can't be found, return this one (simpleNext). This will be the case when // fill=TRUE and the jump lands before 5 too-short lines, for example. for (int attempts = 0; attempts < 5 && ch < eof; attempts++) { const char *ch2 = ch; if (countfields(&ch2) == ncol) return ch; // returns simpleNext here on first attempt, almost all the time ch = skip_to_nextline(ch, eof); } return simpleNext; } double wallclock(void) { double ans = 0; #ifdef HAS_CLOCK_REALTIME struct timespec tp; if (clock_gettime(CLOCK_REALTIME, &tp) == 0) ans = (double) tp.tv_sec + 1e-9 * (double) tp.tv_nsec; #else struct timeval tv; if (gettimeofday(&tv, NULL) == 0) ans = (double) tv.tv_sec + 1e-6 * (double) tv.tv_usec; #endif return ans; } /** * Helper function to print file's size in human-readable format. This will * produce strings such as: * 44.74GiB (48043231704 bytes) * 921MiB (965757797 bytes) * 2.206MiB (2313045 bytes) * 38.69KiB (39615 bytes) * 214 bytes * 1 byte * 0 bytes * The function returns a pointer to a static string buffer, so the caller * should not attempt to deallocate the buffer, or call this function from * multiple threads at the same time, or hold on to the value returned for * extended periods of time. */ static const char* filesize_to_str(const uint64_t fsize) { static const char suffixes[] = { 'T', 'G', 'M', 'K' }; static char output[100]; for (int i = 0; i <= sizeof(suffixes); i++) { int shift = (sizeof(suffixes) - i) * 10; if ((fsize >> shift) == 0) continue; int ndigits = 3; for (; ndigits >= 1; ndigits--) { if ((fsize >> (shift + 12 - ndigits * 3)) == 0) break; } if (ndigits == 0 || (fsize == (fsize >> shift << shift))) { if (i < sizeof(suffixes)) { snprintf(output, sizeof(output), "%"PRIu64"%ciB (%"PRIu64" bytes)", // # notranslate fsize >> shift, suffixes[i], fsize); return output; } } else { snprintf(output, sizeof(output), "%.*f%ciB (%"PRIu64" bytes)", // # notranslate ndigits, (double)fsize / (1LL << shift), suffixes[i], fsize); return output; } } if (fsize == 1) return "1 byte"; snprintf(output, sizeof(output), "%"PRIu64" bytes", fsize); // # notranslate return output; } double copyFile(size_t fileSize) // only called in very very rare cases { double tt = wallclock(); mmp_copy = malloc(fileSize + 1 /* extra \0 */); if (!mmp_copy) return -1.0; // # nocov memcpy(mmp_copy, mmp, fileSize); sof = mmp_copy; eof = (char*)OFFSET_POINTER(mmp_copy, fileSize); return wallclock() - tt; } //============================================================================== // Field parsers // // This section contains functions each designed to parse values of a particular // type from the input string. All these functions have the same signature: // // void parser(FieldParseContext *ctx); // // Here the FieldParseContext structure contains the following fields: // .ch -- pointer to the current parsing location // .targets -- array of memory buffers where parsers store their results // + any other parser-specific fields (for example Field() uses .anchor) // // Each parser is expected to scan the input starting from position `ch`, and // then perform one and only one of the following: // // 1. If the value can be successfully parsed, then it is stored into the // `ctx.targets[sizeof(value)]` buffer, and the parsing location `ctx.ch` // is advanced to point at the first unread byte in the input. // 2. If the value cannot be parsed, then the parser must store an NA value // into the `ctx.targets[sizeof(value)]` buffer. The parsing location // `ctx.ch` should be left unmodified. // // Note that it is not the parser's job to advance the `ctx.targets` pointer -- // this is left to the caller. The reason for this is because we have different // parsing scenarios: // - in the "normal" case the value will be written and the target pointer // advanced; // - in the "trash" case the value will be written but no pointer will be // modified, and we allow the value to be overwritten by a subsequent call; // - in the "typebump" case the value will be written, but some _other_ target // pointer will be advanced. Thus, the value that was just written will be // eventually overwritten, while some other buffer will have a gap filled // with random data (we will reread that column anyways, so it's ok). // // In all cases the caller is responsible to ensure that the `targets[sz]` // buffer is properly allocated and has enough space to write a single value of // size `sz`. // //============================================================================== static void Field(FieldParseContext *ctx) { const char *ch = *ctx->ch; lenOff *target = ctx->targets[sizeof(lenOff)]; // need to skip_white first for the reason that a quoted field might have space before the // quote; e.g. test 1609. We need to skip the space(s) to then switch on quote or not. if ((*ch == ' ' && stripWhite) || (*ch == '\0' && ch < eof)) while(*++ch == ' ' || (*ch == '\0' && ch < eof)); // if sep==' ' the space would have been skipped already and we wouldn't be on space now. const char *fieldStart = ch; if (*ch != quote || quoteRule == QUOTE_RULE_IGNORE_QUOTES || quote == '\0') { // Most common case. Unambiguously not quoted. Simply search for sep|eol. If field contains sep|eol then it should have been quoted and we do not try to heal that. while(!end_of_field(ch)) ch++; // sep, \r, \n or eof will end *ctx->ch = ch; int fieldLen = (int)(ch - fieldStart); //if (stripWhite) { // TODO: do this if and the next one together once in bulk afterwards before push while(fieldLen > 0 && ((ch[-1] == ' ' && stripWhite) || ch[-1] == '\0')) { fieldLen--; ch--; } // this space can't be sep otherwise it would have stopped the field earlier inside end_of_field() //} if ((fieldLen == 0 && blank_is_a_NAstring) || (fieldLen && end_NA_string(fieldStart) == ch)) fieldLen = INT32_MIN; // TODO - speed up by avoiding end_NA_string when there are none target->off = (int32_t)(fieldStart - ctx->anchor); target->len = fieldLen; return; } // else *ch==quote (we don't mind that quoted fields are a little slower e.g. no desire to save switch) // the field is quoted and quotes are correctly escaped (QUOTE_RULE_EMBEDDED_QUOTES_DOUBLED and QUOTE_RULE_EMBEDDED_QUOTES_ESCAPED) // or the field is quoted but quotes are not escaped (QUOTE_RULE_EMBEDDED_QUOTES_NOT_ESCAPED) // or the field is not quoted but the data contains a quote at the start (QUOTE_RULE_EMBEDDED_QUOTES_NOT_ESCAPED too) // What if this string signifies an NA? Will find out after we're done parsing quotes const char *field_after_NA = end_NA_string(fieldStart); fieldStart++; // step over opening quote switch(quoteRule) { case QUOTE_RULE_EMBEDDED_QUOTES_DOUBLED: // quoted with embedded quotes doubled; the final unescaped " must be followed by sep|eol while (*++ch || ch < eof) { if (*ch == quote) { if (ch[1] == quote) { ch++; continue; } break; // found undoubled closing quote } } break; case QUOTE_RULE_EMBEDDED_QUOTES_ESCAPED: // quoted with embedded quotes escaped; the final unescaped " must be followed by sep|eol while (*++ch || ch < eof) { if (*ch == '\\' && (ch[1] == quote || ch[1] == '\\')) { ch++; continue; } if (*ch == quote) break; } break; case QUOTE_RULE_EMBEDDED_QUOTES_NOT_ESCAPED: // (i) quoted (perhaps because the source system knows sep is present) but any quotes were not escaped at all, // so look for ", to define the end. (There might not be any quotes present to worry about, anyway). // (ii) not-quoted but there is a quote at the beginning so it should have been; look for , at the end // If no eol are present inside quoted fields (i.e. rows are simple rows), then this should work ok e.g. test 1453 // since we look for ", and the source system quoted when , is present, looking for ", should work well. // Under this rule, no eol may occur inside fields. { const char *ch2 = ch; while ((*++ch || ch < eof) && *ch != '\n' && *ch != '\r') { if (*ch == quote && end_of_field(ch + 1)) { ch2 = ch; break; } // (*1) regular ", ending; leave *ch on closing quote if (*ch == sep) { // first sep in this field // if there is a ", afterwards but before the next \n, use that; the field was quoted and it's still case (i) above. // Otherwise break here at this first sep as it's case (ii) above (the data contains a quote at the start and no sep) ch2 = ch; while ((*++ch2 || ch2 < eof) && *ch2 != '\n' && *ch2 != '\r') { if (*ch2 == quote && end_of_field(ch2 + 1)) { ch = ch2; // (*2) move on to that first ", -- that's this field's ending break; } } break; } } if (ch != ch2) fieldStart--; // field ending is this sep|eol; neither (*1) or (*2) happened; opening quote wasn't really an opening quote } break; default: // # nocov return; // # nocov Internal error: undefined quote rule } target->len = (int32_t)(ch - fieldStart); target->off = (int32_t)(fieldStart - ctx->anchor); if (*ch == quote) { // quote=='\0' (user set quote="") would have returned earlier above in the same branch as quoteRule 3 ch++; skip_white(&ch); *ctx->ch = ch; } else { *ctx->ch = ch; if (ch == eof && quoteRule != QUOTE_RULE_EMBEDDED_QUOTES_NOT_ESCAPED) { target->off--; target->len++; } // test 1324 where final field has open quote but not ending quote; include the open quote like QUOTE_RULE_EMBEDDED_QUOTES_NOT_ESCAPED while(target->len > 0 && ((ch[-1] == ' ' && stripWhite) || ch[-1] == '\0')) { target->len--; ch--; } // test 1551.6; trailing whitespace in field [67,V37] == "\"\"A\"\" ST " } // Does end-of-field correspond to end-of-possible-NA? if (field_after_NA == ch) target->len = INT32_MIN; } static void str_to_i32_core(const char **pch, int32_t *target, bool parse_date) { const char *ch = *pch; if (*ch == '0' && args.keepLeadingZeros && IS_DIGIT(ch[1]) && !parse_date) return; bool neg = *ch == '-'; ch += (neg || *ch == '+'); const char *start = ch; // to know if at least one digit is present // acc needs to be 64bit so that 5bn (still 10 digits but greater than 4bn) does not overflow. It could be // signed but we use unsigned to be clear it will never be negative uint_fast64_t acc = 0; uint_fast8_t digit; // sep, \r, \n and *eof=='\0' all serve as valid terminators here by dint of being !=[0-9] // see init.c for checks of unsigned uint_fast8_t cast // optimizer should implement 10* as ((x<<2 + x)<<1) or (x<<3 + x<<1) // number significant figures = digits from the first non-zero onwards including trailing zeros while (*ch == '0') ch++; uint_fast32_t sf = 0; while ((digit = AS_DIGIT(ch[sf])) < 10) { acc = 10 * acc + digit; sf++; } ch += sf; // INT32 range is NA==-2147483648(INT32_MIN) then symmetric [-2147483647,+2147483647] so we can just test INT32_MAX // The max (2147483647) happens to be 10 digits long, hence <=10. // Leading 0 (such as 001 and 099 but not 0, +0 or -0) will cause type bump to _full which has the // option to treat as integer or string with further cost. // if ((acc && *start!='0' && acc<=INT32_MAX && (ch-start)<=10) || // (acc==0 && ch-start==1)) { if ((sf || ch > start) && sf <= 10 && acc <= INT32_MAX) { *target = neg ? -(int32_t)acc : (int32_t)acc; *pch = ch; } else { *target = NA_INT32; // empty field ideally, contains NA and fall through to check if NA (in which case this write is important), or just plain invalid } } static void StrtoI32(FieldParseContext *ctx) { str_to_i32_core(ctx->ch, (int32_t*) ctx->targets[sizeof(int32_t)], false); } static void StrtoI64(FieldParseContext *ctx) { const char *ch = *ctx->ch; int64_t *target = ctx->targets[sizeof(int64_t)]; if (*ch == '0' && args.keepLeadingZeros && IS_DIGIT(ch[1])) return; const bool neg = (*ch == '-'); if (neg) ch++; else if (*ch == '+') ch++; const char *start = ch; while (*ch == '0') ch++; uint_fast64_t acc = 0; // important unsigned not signed here; we now need the full unsigned range uint_fast8_t digit; uint_fast32_t sf = 0; while ((digit = AS_DIGIT(ch[sf])) < 10) { acc = 10 * acc + digit; sf++; } ch += sf; // INT64 range is NA==-9223372036854775808(INT64_MIN) then symmetric [-9223372036854775807,+9223372036854775807]. // A 20+ digit number is caught as too large via the field width check <=19, since leading zeros trigger character type not numeric // TODO Check tests exist that +9223372036854775808 and +9999999999999999999 are caught as too large. They are stll 19 wide // and, fortunately, uint64 can hold 9999999999999999999 (19 9's) so that doesn't overflow uint64. //if ((acc && *start!='0' && acc<=INT64_MAX && (ch-start)<=19) || // (acc==0 && ch-start==1)) { if ((sf || ch > start) && sf <= 19 && acc <= INT64_MAX) { *target = neg ? -(int64_t)acc : (int64_t)acc; *ctx->ch = ch; } else { *target = NA_INT64; } } // generate freadLookups.h // TODO: review ERANGE checks and tests; that range outside [1.7e-308,1.7e+308] coerces to [0.0,Inf] /* f = "~/data.table/src/freadLookups.h" cat("const long double pow10lookup[301] = {\n", file=f, append=FALSE) for (i in 0:299) cat("1.0E",i,"L,\n", sep="", file=f, append=TRUE) cat("1.0E300L\n};\n", file=f, append=TRUE) */ // TODO Add faster StrtoD_quick for small precision positive numerics such as prices without a sign or // an E (e.g. $.cents) which don't need I64, long double, or Inf/NAN. Could have more than two levels. /** * Parse "usual" double literals, in the form * * [+|-] (NNN|NNN.|.MMM|NNN.MMM) [(E|e) [+|-] EEE] * * where `NNN`, `MMM`, `EEE` are one or more decimal digits, representing the * whole part, fractional part, and the exponent respectively. * * Right now we do not parse floating numbers that would incur significant loss * of precision, for example `1.2439827340958723094785103` will not be parsed * as a double. */ static void parse_double_regular_core(const char **pch, double *target) { static const int_fast32_t FLOAT_MAX_DIGITS = 18; const char *ch = *pch; *target = NA_FLOAT64; if (*ch == '0' && args.keepLeadingZeros && IS_DIGIT(ch[1])) return; const bool neg = (*ch == '-'); if (neg) ch++; else if (*ch == '+') ch++; const char *start = ch; // beginning of the number, without the initial sign uint_fast64_t acc = 0; // mantissa NNN.MMM as a single 64-bit integer NNNMMM int_fast32_t e = 0; // the number's exponent. The value being parsed is // equal to acc * pow(10,e) uint_fast8_t digit; // temporary variable, holds last scanned digit. while (*ch == '0') ch++; // Skip leading zeros // Read the first, integer part of the floating number (but no more than // FLOAT_MAX_DIGITS digits). int_fast32_t sflimit = FLOAT_MAX_DIGITS; while ((digit = AS_DIGIT(*ch)) < 10 && sflimit) { acc = 10 * acc + digit; sflimit--; ch++; } // If maximum allowed number of digits were read, but more are present -- then // we will read and discard those extra digits, but only if they are followed // by a decimal point (otherwise it's a just big integer, which should be // treated as a string instead of losing precision). if (sflimit == 0 && IS_DIGIT(*ch)) { while (IS_DIGIT(*ch)) { ch++; e++; } if (*ch != dec && *ch != 'e' && *ch != 'E') return; } // Read the fractional part of the number, if it's present if (*ch == dec) { ch++; // skip the decimal point // If the integer part was 0, then leading zeros in the fractional part do // not count against the number's precision. In practice it means that // numbers like 0.00000000000000000000000000000000004 can be read without // loss of precision as 4e-35 (test 1817) if (*ch == '0' && acc == 0) { int_fast32_t k = 0; while (ch[k] == '0') k++; ch += k; e = -k; } // Now read the significant digits in the fractional part of the number int_fast32_t k = 0; while ((digit = AS_DIGIT(ch[k])) < 10 && sflimit) { acc = 10 * acc + digit; k++; sflimit--; } ch += k; e -= k; // If more digits are present, skip them if (sflimit == 0) { while (IS_DIGIT(*ch)) ch++; } // Check that at least 1 digit was present in either the integer or // fractional part ("+1" here accounts for the decimal point char). if (ch == start + 1) return; } // If there is no fractional part, then check that the integer part actually // exists (otherwise it's not a valid number)... else { if (ch == start) return; } // Finally parse the "exponent" part of the number (if present) if (*ch == 'E' || *ch == 'e') { if (ch == start) return; // something valid must be between [+|-] and E, character E alone is invalid. const bool Eneg = ch[1] == '-'; ch += 1/*E*/ + (Eneg) + (ch[1] == '+'); int_fast32_t E = 0; if ((digit = AS_DIGIT(*ch)) < 10) { E = digit; ch++; if ((digit = AS_DIGIT(*ch)) < 10) { E = E * 10 + digit; ch++; if ((digit = AS_DIGIT(*ch)) < 10) { E = E * 10 + digit; ch++; } } } else { // Not a single digit after "E"? Invalid number return; } e += Eneg ? -E : E; } if (e < -350 || e > 350) return; long double r = (long double)acc; if (e < -300 || e > 300) { // Handle extra precision by pre-multiplying the result by pow(10, extra), // and then remove extra from e. // This avoids having to store very small or very large constants that may // fail to be encoded by the compiler, even though the values can actually // be stored correctly. int_fast8_t extra = e < 0 ? e + 300 : e - 300; r = extra < 0 ? r / pow10lookup[-extra] : r * pow10lookup[extra]; e -= extra; } // pow10lookup[301] contains 10^(0:300). Storing negative powers there too // avoids this ternary but is slightly less accurate in some cases, #4461 r = e < 0 ? r / pow10lookup[-e] : r * pow10lookup[e]; *target = (double)(neg ? -r : r); *pch = ch; } static void parse_double_regular(FieldParseContext *ctx) { parse_double_regular_core(ctx->ch, (double*) ctx->targets[sizeof(double)]); } /** * Parses double values, but also understands various forms of NAN literals * (each can possibly be preceded with a `+` or `-` sign): * * nan, inf, NaN, NAN, NaN%, NaNQ, NaNS, qNaN, sNaN, NaN12345, sNaN54321, * 1.#SNAN, 1.#QNAN, 1.#IND, 1.#INF, INF, Inf, Infinity, * #DIV/0!, #VALUE!, #NULL!, #NAME?, #NUM!, #REF!, #N/A * */ static void parse_double_extended(FieldParseContext *ctx) { init_const_literals(); double* target = ctx->targets[sizeof(double)]; const char *ch = *ctx->ch; const bool quoted = (*ch == quote && quote); const bool neg = (*ch == '-'); if (quoted) ch++; if (neg) ch++; else if (*ch == '+') ch++; if (ch[0] == 'n' && ch[1] == 'a' && ch[2] == 'n' && (ch += 3)) goto return_nan; if (ch[0] == 'i' && ch[1] == 'n' && ch[2] == 'f' && (ch += 3)) goto return_inf; if (ch[0] == 'I' && ch[1] == 'N' && ch[2] == 'F' && (ch += 3)) goto return_inf; if (ch[0] == 'I' && ch[1] == 'n' && ch[2] == 'f' && (ch += 3)) { if (ch[0] == 'i' && ch[1] == 'n' && ch[2] == 'i' && ch[3] == 't' && ch[4] == 'y') ch += 5; goto return_inf; } if (ch[0] == 'N' && (ch[1] == 'A' || ch[1] == 'a') && ch[2] == 'N' && (ch += 3)) { if (ch[-2] == 'a' && (*ch == '%' || *ch == 'Q' || *ch == 'S')) ch++; while (IS_DIGIT(*ch)) ch++; goto return_nan; } if ((ch[0] == 'q' || ch[0] == 's') && ch[1] == 'N' && ch[2] == 'a' && ch[3] == 'N' && (ch += 4)) { while (IS_DIGIT(*ch)) ch++; goto return_nan; } if (ch[0] == '1' && ch[1] == '.' && ch[2] == '#') { if ((ch[3] == 'S' || ch[3] == 'Q') && ch[4] == 'N' && ch[5] == 'A' && ch[6] == 'N' && (ch += 7)) goto return_nan; if (ch[3] == 'I' && ch[4] == 'N' && ch[5] == 'D' && (ch += 6)) goto return_nan; if (ch[3] == 'I' && ch[4] == 'N' && ch[5] == 'F' && (ch += 6)) goto return_inf; } if (ch[0] == '#') { // Excel-specific "numbers" if (ch[1] == 'D' && ch[2] == 'I' && ch[3] == 'V' && ch[4] == '/' && ch[5] == '0' && ch[6] == '!' && (ch += 7)) goto return_nan; if (ch[1] == 'V' && ch[2] == 'A' && ch[3] == 'L' && ch[4] == 'U' && ch[5] == 'E' && ch[6] == '!' && (ch += 7)) goto return_nan; if (ch[1] == 'N' && ch[2] == 'U' && ch[3] == 'L' && ch[4] == 'L' && ch[5] == '!' && (ch += 6)) goto return_na; if (ch[1] == 'N' && ch[2] == 'A' && ch[3] == 'M' && ch[4] == 'E' && ch[5] == '?' && (ch += 6)) goto return_na; if (ch[1] == 'N' && ch[2] == 'U' && ch[3] == 'M' && ch[4] == '!' && (ch += 5)) goto return_na; if (ch[1] == 'R' && ch[2] == 'E' && ch[3] == 'F' && ch[4] == '!' && (ch += 5)) goto return_na; if (ch[1] == 'N' && ch[2] == '/' && ch[3] == 'A' && (ch += 4)) goto return_na; } parse_double_regular(ctx); return; return_inf: *target = neg ? -INFD : INFD; goto ok; return_nan: *target = NAND; goto ok; return_na: *target = NA_FLOAT64; ok: if (quoted && *ch != quote) { *target = NA_FLOAT64; } else { *ctx->ch = ch + quoted; } } /** * Parser for hexadecimal doubles as used in Java. * * The numbers are in the following format: * * [+|-] (0x|0X) (0.|1.) HexDigits (p|P) [+|-] DecExponent * * Thus the number has optional sign; followed by hex prefix `0x` or `0X`; * followed by hex significand which may be in the form of either `0.HHHHH...` * or `1.HHHHH...` where `H` are hex-digits (there can be no more than 13 * digits; first form is used for subnormal numbers, second for normal ones); * followed by exponent indicator `p` or `P`; followed by optional exponent * sign; and lastly followed by the exponent which is a decimal number. * * This can be directly converted into IEEE-754 double representation: * * <1 bit: sign> <11 bits: exp+1022> <52 bits: significand> * * This parser also recognizes literals "NaN" and "Infinity" which can be * produced by Java. * * @see http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.2 * @see https://en.wikipedia.org/wiki/IEEE_754-1985 */ static void parse_double_hexadecimal(FieldParseContext *ctx) { init_const_literals(); const char *ch = *ctx->ch; double *target = ctx->targets[sizeof(double)]; *target = NA_FLOAT64; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |