-
Notifications
You must be signed in to change notification settings - Fork 998
/
Copy pathfread.c
2642 lines (2462 loc) · 123 KB
/
fread.c
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>
#include <stdbool.h> // true and false
#else
#include <sys/mman.h> // mmap
#include <sys/stat.h> // fstat for filesize
#include <fcntl.h> // open
#include <unistd.h> // close
#include <stdbool.h> // true and false
#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 bool eol_one_r; // only true very rarely for \r-only files
// Quote rule:
// 0 = Fields may be quoted, any quote inside the field is doubled. This is
// the CSV standard. For example: <<...,"hello ""world""",...>>
// 1 = Fields may be quoted, any quotes inside are escaped with a backslash.
// For example: <<...,"hello \"world\"",...>>
// 2 = 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"",...>>
// 3 = 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",...>>
//
static int 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, fill=false;
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
const char typeName[NUMTYPE][10] = {"drop", "bool8", "bool8", "bool8", "bool8", "bool8", "int32", "int64", "float64", "float64", "float64", "int32", "float64", "string"};
int8_t typeSize[NUMTYPE] = { 0, 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 function.
static double NAND;
static double INFD;
// NAN and INFINITY constants are float, so cast to double once up front.
void init(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);
// note -- because ASSERT is doing literal char array concatenation, it is
// not possible to do translation of its messages without refactoring --
// essentially that would come down to creating f() g() in the code after
// macro expansion, which is not valid. These are internal errors, so just concede.
#define ASSERT(cond, msg, ...) \
if (!(cond)) STOP(_("Internal error in line %d of fread.c, please report on data.table GitHub: " msg), __LINE__, __VA_ARGS__) // # nocov
#define AS_DIGIT(x) (uint_fast8_t)(x - '0')
#define IS_DIGIT(x) AS_DIGIT(x) < 10
//=================================================================================================
//
// 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)
{
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;
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
#endif
mmp = NULL;
}
free(mmp_copy); mmp_copy = NULL;
fileSize = 0;
sep = whiteChar = quote = dec = '\0';
quoteRule = -1;
any_number_like_NAstrings = false;
blank_is_a_NAstring = false;
stripWhite = true;
skipEmptyLines = false;
eol_one_r = false;
fill = false;
// 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; }
/** Return value of `x` clamped to the range [upper, lower] */
static inline int64_t clamp_szt(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 an internal static buffer. Cannot
* be called more than twice per single printf() invocation.
* Parameter `limit` cannot exceed 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).
*/
static const char* strlim(const char *ch, size_t limit) {
static char buf[1002];
static int flip = 0;
char *ptr = buf + 501 * flip;
flip = 1 - flip;
char *ch2 = ptr;
if (limit>500) limit=500;
size_t width = 0;
while ((*ch>'\r' || (*ch!='\0' && *ch!='\r' && *ch!='\n')) && width++<limit) {
*ch2++ = *ch++;
}
*ch2 = '\0';
return ptr;
}
static char *typeLetter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static char *typesAsString(int ncol) {
int nLetters = strlen(typeLetter);
if (NUMTYPE>nLetters) STOP(_("Internal error: NUMTYPE(%d) > nLetters(%d)"), NUMTYPE, nLetters); // # nocov
static char str[101];
int i=0;
if (ncol<=100) {
for (; i<ncol; i++) str[i] = typeLetter[abs(type[i])]; // abs for out-of-sample type bumps (negative)
} else {
for (; i<80; i++) str[i] = typeLetter[abs(type[i])];
str[i++]='.'; str[i++]='.'; str[i++]='.';
for (int j=ncol-10; j<ncol; j++) str[i++] = typeLetter[abs(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;
}
/**
* 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';
}
/**
* 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.
return *ch==sep || ((uint8_t)*ch<=13 && (ch==eof || eol(&ch)));
}
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;
if (sep==' ') while (*ch==' ') ch++; // multiple sep==' ' at the start does not mean sep
skip_white(&ch);
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);
// 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.
while (*ch!='\n' && *ch!='\r' && (*ch!='\0' || ch<eof)) ch++;
if (ch==eof) return eof;
if (eol(&ch)) // move to last byte of the line ending sequence (e.g. \r\r\n would be +2).
ch++; // and then move to first byte of next line
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.
int attempts=0;
while (attempts++<5 && ch<eof) {
const char *ch2 = ch;
if (countfields(&ch2)==ncol) return ch; // returns simpleNext here on first attempt, almost all the time
while (*ch!='\n' && *ch!='\r' && (*ch!='\0' || ch<eof)) ch++;
if (eol(&ch)) ch++;
}
return simpleNext;
}
double wallclock(void)
{
double ans = 0;
#ifdef HAS_CLOCK_REALTIME
struct timespec tp;
if (0==clock_gettime(CLOCK_REALTIME, &tp))
ans = (double) tp.tv_sec + 1e-9 * (double) tp.tv_nsec;
#else
struct timeval tv;
if (0==gettimeofday(&tv, NULL))
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.74GB (48043231704 bytes)
* 921MB (965757797 bytes)
* 2.206MB (2313045 bytes)
* 38.69KB (39615 bytes)
* 214 bytes
* 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(size_t fsize)
{
#define NSUFFIXES 4
#define BUFFSIZE 100
static char suffixes[NSUFFIXES] = {'T', 'G', 'M', 'K'};
static char output[BUFFSIZE];
static const char one_byte[] = "1 byte";
size_t lsize = fsize;
for (int i = 0; i <= NSUFFIXES; i++) {
int shift = (NSUFFIXES - 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 < NSUFFIXES) {
snprintf(output, BUFFSIZE, "%"PRIu64"%cB (%"PRIu64" bytes)",
(uint64_t)(lsize >> shift), suffixes[i], (uint64_t)lsize);
return output;
}
} else {
snprintf(output, BUFFSIZE, "%.*f%cB (%"PRIu64" bytes)",
ndigits, (double)fsize / (1LL << shift), suffixes[i], (uint64_t)lsize);
return output;
}
}
if (fsize == 1) return one_byte;
snprintf(output, BUFFSIZE, "%"PRIu64" bytes", (uint64_t)lsize);
return output;
}
void copyFile(size_t fileSize, const char *msg, bool verbose) // only called in very very rare cases
{
double tt = wallclock();
mmp_copy = (char *)malloc((size_t)fileSize + 1/* extra \0 */);
if (!mmp_copy) STOP(_("Unable to allocate %s of contiguous virtual RAM. %s allocation."), filesize_to_str(fileSize), msg);
memcpy(mmp_copy, mmp, fileSize);
sof = mmp_copy;
eof = (char *)mmp_copy + fileSize;
tt = wallclock()-tt;
if (tt>0.5) DTPRINT(_("Avoidable %.3f seconds. %s time to copy.\n"), tt, msg); // not warning as that could feasibly cause CRAN tests to fail, say, if test machine is heavily loaded
if (verbose) DTPRINT(_(" File copy in RAM took %.3f seconds.\n"), 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 ot 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 = (lenOff*) 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==3 || 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 (quoteRule 0 and 1)
// or the field is quoted but quotes are not escaped (quoteRule 2)
// or the field is not quoted but the data contains a quote at the start (quoteRule 2 too)
fieldStart++; // step over opening quote
switch(quoteRule) {
case 0: // 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 1: // 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 2:
// (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:
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!=2) { target->off--; target->len++; } // test 1324 where final field has open quote but not ending quote; include the open quote like quote rule 2
while(target->len>0 && ((ch[-1]==' ' && stripWhite) || ch[-1]=='\0')) { target->len--; ch--; } // test 1551.6; trailing whitespace in field [67,V37] == "\"\"A\"\" ST "
}
}
static void str_to_i32_core(const char **pch, int32_t *target)
{
const char *ch = *pch;
if (*ch=='0' && args.keepLeadingZeros && IS_DIGIT(ch[1])) 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)]);
}
static void StrtoI64(FieldParseContext *ctx)
{
const char *ch = *(ctx->ch);
int64_t *target = (int64_t*) ctx->targets[sizeof(int64_t)];
if (*ch=='0' && args.keepLeadingZeros && IS_DIGIT(ch[1])) return;
bool neg = *ch=='-';
ch += (neg || *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)
{
#define FLOAT_MAX_DIGITS 18
const char *ch = *pch;
if (*ch=='0' && args.keepLeadingZeros && IS_DIGIT(ch[1])) return;
bool neg, Eneg;
ch += (neg = *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') goto fail;
}
// 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) goto fail;
}
// 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) goto fail;
}
// Finally parse the "exponent" part of the number (if present)
if (*ch=='E' || *ch=='e') {
if (ch==start) goto fail; // something valid must be between [+|-] and E, character E alone is invalid.
ch += 1/*E*/ + (Eneg = ch[1]=='-') + (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
goto fail;
}
e += Eneg? -E : E;
}
if (e<-350 || e>350) goto fail;
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;
return;
fail:
*target = NA_FLOAT64;
}
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)
{
const char *ch = *(ctx->ch);
double *target = (double*) ctx->targets[sizeof(double)];
bool neg, quoted;
init();
ch += (quoted = (*ch==quote && quote));
ch += (neg = (*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)
{
const char *ch = *(ctx->ch);
double *target = (double*) ctx->targets[sizeof(double)];
uint64_t neg;
bool Eneg, subnormal = 0;
init();
ch += (neg = (*ch=='-')) + (*ch=='+');
if (ch[0]=='0' && (ch[1]=='x' || ch[1]=='X') &&
(ch[2]=='1' || (subnormal = ch[2]=='0')) && ch[3]=='.') {
ch += 4;
uint64_t acc = 0;
uint8_t digit;
const char *ch0 = ch;
while ((digit = hexdigits[(uint8_t)(*ch)]) < 16) {
acc = (acc << 4) + digit;
ch++;
}
size_t ndigits = (uint_fast8_t)(ch - ch0);
if (ndigits > 13 || !(*ch=='p' || *ch=='P')) goto fail;
acc <<= (13 - ndigits) * 4;
ch += 1 + (Eneg = ch[1]=='-') + (ch[1]=='+');
uint64_t E = 0;
while ((digit = AS_DIGIT(*ch)) < 10) {
E = 10*E + digit;
ch++;
}
E = 1023 + (Eneg? -E : E) - subnormal;
if (subnormal ? E : (E<1 || E>2046)) goto fail;
*((uint64_t*)target) = (neg << 63) | (E << 52) | (acc);
*(ctx->ch) = ch;
return;
}
if (ch[0]=='N' && ch[1]=='a' && ch[2]=='N') {
*target = NA_FLOAT64;
*(ctx->ch) = ch + 3;
return;
}
if (ch[0]=='I' && ch[1]=='n' && ch[2]=='f' && ch[3]=='i' &&
ch[4]=='n' && ch[5]=='i' && ch[6]=='t' && ch[7]=='y') {
*target = neg ? -INFD : INFD;
*(ctx->ch) = ch + 8;
return;
}
fail:
*target = NA_FLOAT64;
}
/*
f = 'src/freadLookups.h'
cat('const uint8_t cumDaysCycleYears[401] = {\n', file=f, append=TRUE)
t = format(as.double(difftime(as.Date(sprintf('%04d-01-01', 1600:1999)), .Date(0), units='days')))
rows = paste0(apply(matrix(t, ncol = 4L, byrow = TRUE), 1L, paste, collapse = ', '), ',\n')
cat(rows, sep='', file=f, append=TRUE)
cat(146097, '// total days in 400 years\n};\n', sep = '', file=f, append=TRUE)
*/
static void parse_iso8601_date_core(const char **pch, int32_t *target)
{
const char *ch = *pch;
int32_t year=0, month=0, day=0;
str_to_i32_core(&ch, &year);
// .Date(.Machine$integer.max*c(-1, 1)):
// -5877641-06-24 -- 5881580-07-11
// rather than fiddle with dates within those terminal years (unlikely
// to be showing up in data sets any time soon), just truncate towards 0
if (year == NA_INT32 || year < -5877640 || year > 5881579 || *ch != '-')
goto fail;
// Multiples of 4, excluding 3/4 of centuries
bool isLeapYear = year % 4 == 0 && (year % 100 != 0 || year/100 % 4 == 0);
ch++;
str_to_i32_core(&ch, &month);
if (month == NA_INT32 || month < 1 || month > 12 || *ch != '-')
goto fail;
ch++;
str_to_i32_core(&ch, &day);
if (day == NA_INT32 || day < 1 ||
(day > (isLeapYear ? leapYearDays[month-1] : normYearDays[month-1])))
goto fail;
*target =
(year/400 - 4)*cumDaysCycleYears[400] + // days to beginning of 400-year cycle
cumDaysCycleYears[year % 400] + // days to beginning of year within 400-year cycle
(isLeapYear ? cumDaysCycleMonthsLeap[month-1] : cumDaysCycleMonthsNorm[month-1]) + // days to beginning of month within year
day-1; // day within month (subtract 1: 1970-01-01 -> 0)
*pch = ch;
return;
fail:
*target = NA_INT32;
}
static void parse_iso8601_date(FieldParseContext *ctx) {
parse_iso8601_date_core(ctx->ch, (int32_t*) ctx->targets[sizeof(int32_t)]);