-
Notifications
You must be signed in to change notification settings - Fork 2
/
fastcsv.d
531 lines (466 loc) · 14.5 KB
/
fastcsv.d
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
/**
* Experimental fast CSV reader.
*
* Based on RFC 4180.
*/
module fastcsv;
/**
* Reads CSV data from the given filename.
*/
auto csvFromUtf8File(string filename)
{
import std.file : read;
return csvToArray(cast(string) read(filename));
}
private char[] filterQuotes(dchar quote)(const(char)[] str) pure
{
auto buf = new char[str.length];
size_t j = 0;
for (size_t i = 0; i < str.length; i++)
{
if (str[i] == quote)
{
buf[j++] = '"';
i++;
if (i >= str.length)
break;
if (str[i] == quote)
continue;
}
buf[j++] = str[i];
}
return buf[0 .. j];
}
/**
* Parse CSV data into an input range of records.
*
* Params:
* fieldDelim = The field delimiter (default: ',')
* quote = The quote character (default: '"')
* input = The data in CSV format.
*
* Returns:
* An input range of records, each of which is an array of fields.
*
* Bugs:
* Does not do any validation on the input; will produce nonsensical results
* if input is malformed.
*
* Cannot handle records with more than 4096 fields each. (This limit can be
* statically increased by increasing fieldBlockSize.)
*/
auto csvByRecord(dchar fieldDelim=',', dchar quote='"')(const(char)[] input)
{
struct Result
{
private enum fieldBlockSize = 1 << 16;
private const(char)[] data;
private const(char)[][] fields;
private size_t i, curField;
bool empty = true;
const(char)[][] front;
this(const(char)[] input)
{
data = input;
fields = new const(char)[][fieldBlockSize];
i = 0;
curField = 0;
empty = (input.length == 0);
parseNextRecord();
}
private void parseNextRecord()
{
size_t firstField = curField;
void allocNewBlock()()
{
// Fields block is full; copy current record fields into new
// block so that they are contiguous.
auto nextFields = new const(char)[][fieldBlockSize];
nextFields[0 .. curField - firstField] =
fields[firstField .. curField];
//fields.length = firstField; // release unused memory?
curField = curField - firstField;
firstField = 0;
fields = nextFields;
}
while (i < data.length && data[i] != '\n' && data[i] != '\r')
{
// Parse fields
size_t firstChar, lastChar;
bool hasDoubledQuotes = false;
if (data[i] == quote)
{
import std.algorithm : max;
i++;
firstChar = i;
while (i < data.length)
{
if (data[i] == quote)
{
i++;
if (i >= data.length || data[i] != quote)
break;
hasDoubledQuotes = true;
}
i++;
}
assert(i-1 < data.length);
lastChar = max(firstChar, i-1);
}
else
{
firstChar = i;
while (i < data.length && data[i] != fieldDelim &&
data[i] != '\n' && data[i] != '\r')
{
i++;
}
lastChar = i;
}
if (curField >= fields.length)
allocNewBlock();
assert(curField < fields.length);
if (hasDoubledQuotes)
fields[curField++] = filterQuotes!quote(
data[firstChar .. lastChar]);
else
fields[curField++] = data[firstChar .. lastChar];
// Skip over field delimiter
if (i < data.length && data[i] == fieldDelim)
{
i++;
// Corner case: trailing delimiter on line, should generate
// empty field.
if (data[i] == '\n' || data[i] == '\r')
{
if (curField >= fields.length)
allocNewBlock();
fields[curField++] = "";
}
}
}
front = fields[firstField .. curField];
// Skip over record delimiter(s)
while (i < data.length && (data[i] == '\n' || data[i] == '\r'))
i++;
}
void popFront()
{
if (i >= data.length)
{
empty = true;
front = [];
}
else
parseNextRecord();
}
}
return Result(input);
}
/**
* Parses CSV string data into an array of records.
*
* Params:
* fieldDelim = The field delimiter (default: ',')
* quote = The quote character (default: '"')
* input = The data in CSV format.
*
* Returns:
* An array of records, each of which is an array of fields.
*/
auto csvToArray(dchar fieldDelim=',', dchar quote='"')(const(char)[] input)
{
import core.memory : GC;
import std.array : array;
GC.disable();
auto result = input.csvByRecord!(fieldDelim, quote).array;
GC.collect();
GC.enable();
return result;
}
unittest
{
auto sampleData =
`123,abc,"mno pqr",0` ~ "\n" ~
`456,def,"stuv wx",1` ~ "\n" ~
`78,ghijk,"yx",2`;
auto parsed = csvToArray(sampleData);
assert(parsed == [
[ "123", "abc", "mno pqr", "0" ],
[ "456", "def", "stuv wx", "1" ],
[ "78", "ghijk", "yx", "2" ]
]);
}
unittest
{
auto dosData =
`123,aa,bb,cc` ~ "\r\n" ~
`456,dd,ee,ff` ~ "\r\n" ~
`789,gg,hh,ii` ~ "\r\n";
auto parsed = csvToArray(dosData);
assert(parsed == [
[ "123", "aa", "bb", "cc" ],
[ "456", "dd", "ee", "ff" ],
[ "789", "gg", "hh", "ii" ]
]);
}
unittest
{
// Quoted fields that contains newlines and delimiters
auto nastyData =
`123,abc,"ha ha ` ~ "\n" ~
`ha this is a split value",567` ~ "\n" ~
`321,"a,comma,b",def,111` ~ "\n";
auto parsed = csvToArray(nastyData);
assert(parsed == [
[ "123", "abc", "ha ha \nha this is a split value", "567" ],
[ "321", "a,comma,b", "def", "111" ]
]);
}
unittest
{
// Quoted fields that contain quotes
// (Note: RFC-4180 does not allow doubled quotes in unquoted fields)
auto nastyData =
`123,"a b ""haha"" c",456` ~ "\n";
auto parsed = csvToArray(nastyData);
assert(parsed == [
[ "123", `a b "haha" c`, "456" ]
]);
}
// Boundary condition checks
unittest
{
auto badData = `123,345,"def""`;
auto parsed = csvToArray(badData); // should not crash
auto moreBadData = `123,345,"a"`;
parsed = csvToArray(moreBadData); // should not crash
auto yetMoreBadData = `123,345,"`;
parsed = csvToArray(yetMoreBadData); // should not crash
auto emptyField = `123,,456`;
parsed = csvToArray(emptyField);
assert(parsed == [ [ "123", "", "456" ] ]);
}
static if (__VERSION__ < 2067UL)
{
// Copied from std.traits, to fill up lack in older versions of Phobos
import std.typetuple : staticMap;
private enum NameOf(alias T) = T.stringof;
template isNested(T)
if(is(T == class) || is(T == struct) || is(T == union))
{
enum isNested = __traits(isNested, T);
}
template FieldNameTuple(T)
{
static if (is(T == struct) || is(T == union))
alias FieldNameTuple = staticMap!(NameOf, T.tupleof[0 .. $ - isNested!T]);
else static if (is(T == class))
alias FieldNameTuple = staticMap!(NameOf, T.tupleof);
else
alias FieldNameTuple = TypeTuple!"";
}
}
/**
* Transcribe CSV data into an array of structs.
*
* Params:
* S = The type of the struct each record must conform to.
* fieldDelim = The field delimiter (default: ',')
* quote = The quote character (default: '"')
* input = The data in CSV format.
*
* Returns:
* An array of S.
*
* Bugs:
* Cannot handle strings larger than 64KB each. (This limit can be statically
* raised by increasing stringBufSize.)
*/
auto csvByStruct(S, dchar fieldDelim=',', dchar quote='"')(const(char)[] input)
if (is(S == struct))
{
struct Result
{
private enum stringBufSize = 1 << 16;
private const(char)[] data;
private char[] stringBuf;
private size_t i, curStringIdx;
bool empty = true;
S front;
this(const(char)[] input)
{
data = input;
stringBuf = new char[stringBufSize];
i = 0;
curStringIdx = 0;
if (input.length > 0)
{
empty = false;
parseHeader();
if (input.length > 0)
parseNextRecord();
}
}
const(char)[] parseField() pure
{
size_t firstChar, lastChar;
bool hasDoubledQuotes = false;
if (data[i] == quote)
{
import std.algorithm : max;
i++;
firstChar = i;
while (i < data.length)
{
if (data[i] == quote)
{
i++;
if (i >= data.length || data[i] != quote)
break;
hasDoubledQuotes = true;
}
i++;
}
assert(i-1 < data.length);
lastChar = max(firstChar, i-1);
}
else
{
firstChar = i;
while (i < data.length && data[i] != fieldDelim &&
data[i] != '\n' && data[i] != '\r')
{
i++;
}
lastChar = i;
}
return (hasDoubledQuotes) ?
filterQuotes!quote(data[firstChar .. lastChar]) :
data[firstChar .. lastChar];
}
void parseHeader()
{
static if (__VERSION__ >= 2067UL)
import std.traits : FieldNameTuple;
assert(i < data.length);
foreach (field; FieldNameTuple!S)
{
if (parseField() != field)
throw new Exception(
"CSV fields do not match struct fields");
// Skip over field delimiter
if (i < data.length && data[i] == fieldDelim)
i++;
}
if (i < data.length && data[i] != '\n' && data[i] != '\r')
throw new Exception("CSV fields do not match struct fields");
// Skip over record delimiter(s)
while (i < data.length && (data[i] == '\n' || data[i] == '\r'))
i++;
}
void parseNextRecord()
{
import std.conv : to;
static if (__VERSION__ >= 2067UL)
import std.traits : FieldNameTuple;
assert(i < data.length);
foreach (field; FieldNameTuple!S)
{
alias Value = typeof(__traits(getMember, front, field));
// Convert value
const(char)[] strval = parseField();
static if (is(Value == string))
{
// Optimization for string fields: instead of many small
// string allocations, consolidate strings into a string
// buffer and take slices of it.
if (strval.length + curStringIdx >= stringBuf.length)
{
// String buffer full; allocate new buffer.
stringBuf = new char[stringBufSize];
curStringIdx = 0;
}
stringBuf[curStringIdx .. curStringIdx + strval.length] =
strval[0 .. $];
// Since we never take overlapping slices of stringBuf,
// it's safe to assume uniqueness here.
import std.exception : assumeUnique;
__traits(getMember, front, field) = assumeUnique(strval);
}
else
__traits(getMember, front, field) = strval.to!Value;
// Skip over field delimiter
if (i < data.length && data[i] == fieldDelim)
i++;
}
if (i < data.length && data[i] != '\n' && data[i] != '\r')
throw new Exception("Record does not match struct");
// Skip over record delimiter(s)
while (i < data.length && (data[i] == '\n' || data[i] == '\r'))
i++;
}
void popFront()
{
if (i >= data.length)
{
empty = true;
front = front.init;
}
else
parseNextRecord();
}
}
return Result(input);
}
unittest
{
import std.algorithm.comparison : equal;
struct S
{
string name;
int year;
int month;
int day;
}
auto input =
`name,year,month,day` ~"\n"~
`John Smith,1995,1,1` ~"\n"~
`Jane Doe,1996,2,14` ~"\n"~
`Albert Donahue,1997,3,30`;
auto r = input.csvByStruct!S;
assert(r.equal([
S("John Smith", 1995, 1, 1),
S("Jane Doe", 1996, 2, 14),
S("Albert Donahue", 1997, 3, 30)
]));
// Test failure cases
import std.exception : assertThrown;
struct T
{
string name;
int age;
int customerId;
}
assertThrown(input.csvByStruct!T.front);
auto badInput =
`name,year,month,day` ~"\n"~
`1995,Jane Doe,2,14`;
assertThrown(badInput.csvByStruct!S.front);
}
version(none)
unittest
{
auto data = csvFromUtf8File("ext/cbp13co.txt");
import std.stdio;
writefln("%d records", data.length);
}
// issue #2
unittest
{
import std.conv : text;
auto data = "1,2,\na,b,c";
auto parsed = csvToArray(data);
assert(parsed == [[ "1", "2", "" ], [ "a", "b", "c" ]], parsed.text);
}
// vim:set ai sw=4 ts=4 et: