-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathreader.rs
2005 lines (1842 loc) · 67.4 KB
/
reader.rs
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
use core::fmt;
use crate::Terminator;
// BE ADVISED
//
// This may just be one of the more complicated CSV parsers you'll come across.
// The implementation never allocates and consists of both a functional NFA
// parser and a DFA parser. The DFA parser is the work horse and we could elide
// much of the work involved in making the NFA parser work, but the NFA parser
// is much easier to debug. The NFA parser is tested alongside the DFA parser,
// so they should never be out of sync.
//
// The basic structure of the implementation is to encode the NFA parser as
// an explicit state machine in code. The DFA is then generated by populating
// a transition table on the stack by exhaustively enumerating all possible
// states on all possible inputs (this is possible because the number of states
// and the number of inputs is very small).
//
// Note that some pieces of the NFA parser (such as the NFA state machine) are
// required. In particular, the translation from the NFA to the DFA depends on
// the configuration of the CSV parser as given by the caller, and indeed, this
// is one of the key performance benefits of the DFA: it doesn't have any
// overhead (other than a bigger transition table) associated with the number
// of configuration options.
//
// ADVICE FOR HACKERS
//
// This code is too clever for its own good. As such, changes to some parts of
// the code may have a non-obvious impact on other parts. This is mostly
// motivated by trying to keep the DFA transition table as small as possible,
// since it is stored on the stack. Here are some tips that may save you some
// time:
//
// * If you add a new NFA state, then you also need to consider how it impacts
// the DFA. If all of the incoming transitions into an NFA state are
// epsilon transitions, then it probably isn't materialized in the DFA.
// If the NFA state indicates that a field or a record has been parsed, then
// it should be considered final. Let the comments in `NfaState` be your
// guide.
// * If you add a new configuration knob to the parser, then you may need to
// modify the `TRANS_CLASSES` constant below. The `TRANS_CLASSES` constant
// indicates the total number of discriminating bytes in the DFA. And if you
// modify `TRANS_CLASSES`, you probably also need to modify `build_dfa` to
// add a new class. For example, in order to add parsing support for
// comments, I bumped `TRANS_CLASSES` from `6` to `7` and added the comment
// byte (if one exists) to the list of classes in `build_dfa`.
// * The special DFA start state doubles as the final state once all input
// from the caller has been exhausted. We must be careful to guard this
// case analysis on whether the input is actually exhausted, since the start
// state is an otherwise valid state.
/// A pull based CSV reader.
///
/// This reader parses CSV data using a finite state machine. Callers can
/// extract parsed data incrementally using one of the `read` methods.
///
/// Note that this CSV reader is somewhat encoding agnostic. The source data
/// needs to be at least ASCII compatible. There is no support for specifying
/// the full gamut of Unicode delimiters/terminators/quotes/escapes. Instead,
/// any byte can be used, although callers probably want to stick to the ASCII
/// subset (`<= 0x7F`).
///
/// # Usage
///
/// A reader has two different ways to read CSV data, each with their own
/// trade offs.
///
/// * `read_field` - Copies a single CSV field into an output buffer while
/// unescaping quotes. This is simple to use and doesn't require storing an
/// entire record contiguously in memory, but it is slower.
/// * `read_record` - Copies an entire CSV record into an output buffer while
/// unescaping quotes. The ending positions of each field are copied into
/// an additional buffer. This is harder to use and requires larger output
/// buffers, but it is faster than `read_field` since it amortizes more
/// costs.
///
/// # RFC 4180
///
/// [RFC 4180](https://tools.ietf.org/html/rfc4180)
/// is the closest thing to a specification for CSV data. Unfortunately,
/// CSV data that is seen in the wild can vary significantly. Often, the CSV
/// data is outright invalid. Instead of fixing the producers of bad CSV data,
/// we have seen fit to make consumers much more flexible in what they accept.
/// This reader continues that tradition, and therefore, isn't technically
/// compliant with RFC 4180. In particular, this reader will never return an
/// error and will always find *a* parse.
///
/// Here are some detailed differences from RFC 4180:
///
/// * CRLF, LF and CR are each treated as a single record terminator by
/// default.
/// * Records are permitted to be of varying length.
/// * Empty lines (that do not include other whitespace) are ignored.
#[derive(Clone, Debug)]
pub struct Reader {
/// A table-based DFA for parsing CSV.
dfa: Dfa,
/// The current DFA state, if the DFA is used.
dfa_state: DfaState,
/// The current NFA state, if the NFA is used.
nfa_state: NfaState,
/// The delimiter that separates fields.
delimiter: u8,
/// The terminator that separates records.
term: Terminator,
/// The quotation byte.
quote: u8,
/// Whether to recognize escaped quotes.
escape: Option<u8>,
/// Whether to recognized doubled quotes.
double_quote: bool,
/// If enabled, lines beginning with this byte are ignored.
comment: Option<u8>,
/// If enabled (the default), then quotes are respected. When disabled,
/// quotes are not treated specially.
quoting: bool,
/// Whether to use the NFA for parsing.
///
/// Generally this is for debugging. There's otherwise no good reason
/// to avoid the DFA.
use_nfa: bool,
/// The current line number.
line: u64,
/// Whether this parser has ever read anything.
has_read: bool,
/// The current position in the output buffer when reading a record.
output_pos: usize,
}
impl Default for Reader {
fn default() -> Reader {
Reader {
dfa: Dfa::new(),
dfa_state: DfaState::start(),
nfa_state: NfaState::StartRecord,
delimiter: b',',
term: Terminator::default(),
quote: b'"',
escape: None,
double_quote: true,
comment: None,
quoting: true,
use_nfa: false,
line: 1,
has_read: false,
output_pos: 0,
}
}
}
/// Builds a CSV reader with various configuration knobs.
///
/// This builder can be used to tweak the field delimiter, record terminator
/// and more for parsing CSV. Once a CSV `Reader` is built, its configuration
/// cannot be changed.
#[derive(Debug, Default)]
pub struct ReaderBuilder {
rdr: Reader,
}
impl ReaderBuilder {
/// Create a new builder.
pub fn new() -> ReaderBuilder {
ReaderBuilder::default()
}
/// Build a CSV parser from this configuration.
pub fn build(&self) -> Reader {
let mut rdr = self.rdr.clone();
rdr.build_dfa();
rdr
}
/// The field delimiter to use when parsing CSV.
///
/// The default is `b','`.
pub fn delimiter(&mut self, delimiter: u8) -> &mut ReaderBuilder {
self.rdr.delimiter = delimiter;
self
}
/// The record terminator to use when parsing CSV.
///
/// A record terminator can be any single byte. The default is a special
/// value, `Terminator::CRLF`, which treats any occurrence of `\r`, `\n`
/// or `\r\n` as a single record terminator.
pub fn terminator(&mut self, term: Terminator) -> &mut ReaderBuilder {
self.rdr.term = term;
self
}
/// The quote character to use when parsing CSV.
///
/// The default is `b'"'`.
pub fn quote(&mut self, quote: u8) -> &mut ReaderBuilder {
self.rdr.quote = quote;
self
}
/// The escape character to use when parsing CSV.
///
/// In some variants of CSV, quotes are escaped using a special escape
/// character like `\` (instead of escaping quotes by doubling them).
///
/// By default, recognizing these idiosyncratic escapes is disabled.
pub fn escape(&mut self, escape: Option<u8>) -> &mut ReaderBuilder {
self.rdr.escape = escape;
self
}
/// Enable double quote escapes.
///
/// This is enabled by default, but it may be disabled. When disabled,
/// doubled quotes are not interpreted as escapes.
pub fn double_quote(&mut self, yes: bool) -> &mut ReaderBuilder {
self.rdr.double_quote = yes;
self
}
/// Enable or disable quoting.
///
/// This is enabled by default, but it may be disabled. When disabled,
/// quotes are not treated specially.
pub fn quoting(&mut self, yes: bool) -> &mut ReaderBuilder {
self.rdr.quoting = yes;
self
}
/// The comment character to use when parsing CSV.
///
/// If the start of a record begins with the byte given here, then that
/// line is ignored by the CSV parser.
///
/// This is disabled by default.
pub fn comment(&mut self, comment: Option<u8>) -> &mut ReaderBuilder {
self.rdr.comment = comment;
self
}
/// A convenience method for specifying a configuration to read ASCII
/// delimited text.
///
/// This sets the delimiter and record terminator to the ASCII unit
/// separator (`\x1F`) and record separator (`\x1E`), respectively.
pub fn ascii(&mut self) -> &mut ReaderBuilder {
self.delimiter(b'\x1F').terminator(Terminator::Any(b'\x1E'))
}
/// Enable or disable the NFA for parsing CSV.
///
/// This is intended to be a debug option useful for debugging. The NFA
/// is always slower than the DFA.
#[doc(hidden)]
pub fn nfa(&mut self, yes: bool) -> &mut ReaderBuilder {
self.rdr.use_nfa = yes;
self
}
}
/// The result of parsing at most one field from CSV data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReadFieldResult {
/// The caller provided input was exhausted before the end of a field or
/// record was found.
InputEmpty,
/// The caller provided output buffer was filled before an entire field
/// could be written to it.
OutputFull,
/// The end of a field was found.
///
/// Note that when `record_end` is true, then the end of this field also
/// corresponds to the end of a record.
Field {
/// Whether this was the last field in a record or not.
record_end: bool,
},
/// All CSV data has been read.
///
/// This state can only be returned when an empty input buffer is provided
/// by the caller.
End,
}
impl ReadFieldResult {
fn from_nfa(
state: NfaState,
inpdone: bool,
outdone: bool,
) -> ReadFieldResult {
match state {
NfaState::End => ReadFieldResult::End,
NfaState::EndRecord | NfaState::CRLF => {
ReadFieldResult::Field { record_end: true }
}
NfaState::EndFieldDelim => {
ReadFieldResult::Field { record_end: false }
}
_ => {
assert!(!state.is_field_final());
if !inpdone && outdone {
ReadFieldResult::OutputFull
} else {
ReadFieldResult::InputEmpty
}
}
}
}
}
/// The result of parsing at most one field from CSV data while ignoring the
/// output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReadFieldNoCopyResult {
/// The caller provided input was exhausted before the end of a field or
/// record was found.
InputEmpty,
/// The end of a field was found.
///
/// Note that when `record_end` is true, then the end of this field also
/// corresponds to the end of a record.
Field {
/// Whether this was the last field in a record or not.
record_end: bool,
},
/// All CSV data has been read.
///
/// This state can only be returned when an empty input buffer is provided
/// by the caller.
End,
}
/// The result of parsing at most one record from CSV data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReadRecordResult {
/// The caller provided input was exhausted before the end of a record was
/// found.
InputEmpty,
/// The caller provided output buffer was filled before an entire field
/// could be written to it.
OutputFull,
/// The caller provided output buffer of field end poisitions was filled
/// before the next field could be parsed.
OutputEndsFull,
/// The end of a record was found.
Record,
/// All CSV data has been read.
///
/// This state can only be returned when an empty input buffer is provided
/// by the caller.
End,
}
impl ReadRecordResult {
fn is_record(&self) -> bool {
*self == ReadRecordResult::Record
}
fn from_nfa(
state: NfaState,
inpdone: bool,
outdone: bool,
endsdone: bool,
) -> ReadRecordResult {
match state {
NfaState::End => ReadRecordResult::End,
NfaState::EndRecord | NfaState::CRLF => ReadRecordResult::Record,
_ => {
assert!(!state.is_record_final());
if !inpdone && outdone {
ReadRecordResult::OutputFull
} else if !inpdone && endsdone {
ReadRecordResult::OutputEndsFull
} else {
ReadRecordResult::InputEmpty
}
}
}
}
}
/// The result of parsing at most one record from CSV data while ignoring
/// output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReadRecordNoCopyResult {
/// The caller provided input was exhausted before the end of a record was
/// found.
InputEmpty,
/// The end of a record was found.
Record,
/// All CSV data has been read.
///
/// This state can only be returned when an empty input buffer is provided
/// by the caller.
End,
}
/// What should be done with input bytes during an NFA transition
#[derive(Clone, Debug, Eq, PartialEq)]
enum NfaInputAction {
// Do not consume an input byte
Epsilon,
// Copy input byte to a caller-provided output buffer
CopyToOutput,
// Consume but do not copy input byte (for example, seeing a field
// delimiter will consume an input byte but should not copy it to the
// output buffer.
Discard,
}
/// An NFA state is a state that can be visited in the NFA parser.
///
/// Given the simplicity of the machine, a subset of NFA states double as DFA
/// states. NFA states that only have incoming epsilon transitions are
/// optimized out when converting the machine to a DFA.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum NfaState {
// These states aren't used in the DFA, so we
// assign them meaningless numbers.
EndFieldTerm = 200,
InRecordTerm = 201,
End = 202,
// All states below are DFA states.
StartRecord = 0,
StartField = 1,
InField = 2,
InQuotedField = 3,
InEscapedQuote = 4,
InDoubleEscapedQuote = 5,
InComment = 6,
// All states below are "final field" states.
// Namely, they indicate that a field has been parsed.
EndFieldDelim = 7,
// All states below are "final record" states.
// Namely, they indicate that a record has been parsed.
EndRecord = 8,
CRLF = 9,
}
/// A list of NFA states that have an explicit representation in the DFA.
const NFA_STATES: &'static [NfaState] = &[
NfaState::StartRecord,
NfaState::StartField,
NfaState::EndFieldDelim,
NfaState::InField,
NfaState::InQuotedField,
NfaState::InEscapedQuote,
NfaState::InDoubleEscapedQuote,
NfaState::InComment,
NfaState::EndRecord,
NfaState::CRLF,
];
impl NfaState {
/// Returns true if this state indicates that a field has been parsed.
fn is_field_final(&self) -> bool {
match *self {
NfaState::End
| NfaState::EndRecord
| NfaState::CRLF
| NfaState::EndFieldDelim => true,
_ => false,
}
}
/// Returns true if this state indicates that a record has been parsed.
fn is_record_final(&self) -> bool {
match *self {
NfaState::End | NfaState::EndRecord | NfaState::CRLF => true,
_ => false,
}
}
}
impl Reader {
/// Create a new CSV reader with a default parser configuration.
pub fn new() -> Reader {
ReaderBuilder::new().build()
}
/// Reset the parser such that it behaves as if it had never been used.
///
/// This may be useful when reading CSV data in a random access pattern.
pub fn reset(&mut self) {
self.dfa_state = self.dfa.new_state(NfaState::StartRecord);
self.nfa_state = NfaState::StartRecord;
self.line = 1;
self.has_read = false;
}
/// Return the current line number as measured by the number of occurrences
/// of `\n`.
///
/// Line numbers starts at `1` and are reset when `reset` is called.
pub fn line(&self) -> u64 {
self.line
}
/// Set the line number.
///
/// This is useful after a call to `reset` where the caller knows the
/// line number from some additional context.
pub fn set_line(&mut self, line: u64) {
self.line = line;
}
/// Parse a single CSV field in `input` and copy field data to `output`.
///
/// This routine requires a caller provided buffer of CSV data as the
/// `input` and a caller provided buffer, `output`, in which to store field
/// data extracted from `input`. The field data copied to `output` will
/// have its quotes unescaped.
///
/// Calling this routine parses at most a single field and returns
/// three values indicating the state of the parser. The first value, a
/// `ReadFieldResult`, tells the caller what to do next. For example, if
/// the entire input was read or if the output buffer was filled before
/// a full field had been read, then `ReadFieldResult::InputEmpty` or
/// `ReadFieldResult::OutputFull` is returned, respectively. See the
/// documentation for `ReadFieldResult` for more details.
///
/// The other two values returned correspond to the number of bytes
/// read from `input` and written to `output`, respectively.
///
/// # Termination
///
/// This reader interprets an empty `input` buffer as an indication that
/// there is no CSV data left to read. Namely, when the caller has
/// exhausted all CSV data, the caller should continue to call `read` with
/// an empty input buffer until `ReadFieldResult::End` is returned.
///
/// # Errors
///
/// This CSV reader can never return an error. Instead, it prefers *a*
/// parse over *no* parse.
pub fn read_field(
&mut self,
input: &[u8],
output: &mut [u8],
) -> (ReadFieldResult, usize, usize) {
let (input, bom_nin) = self.strip_utf8_bom(input);
let (res, nin, nout) = if self.use_nfa {
self.read_field_nfa(input, output)
} else {
self.read_field_dfa(input, output)
};
self.has_read = true;
(res, nin + bom_nin, nout)
}
/// Parse a single CSV record in `input` and copy each field contiguously
/// to `output`, with the end position of each field written to `ends`.
///
/// **NOTE**: This method is more cumbersome to use than `read_field`, but
/// it can be faster since it amortizes more work.
///
/// This routine requires a caller provided buffer of CSV data as the
/// `input` and two caller provided buffers to store the unescaped field
/// data (`output`) and the end position of each field in the record
/// (`fields`).
///
/// Calling this routine parses at most a single record and returns four
/// values indicating the state of the parser. The first value, a
/// `ReadRecordResult`, tells the caller what to do next. For example, if
/// the entire input was read or if the output buffer was filled before a
/// full field had been read, then `ReadRecordResult::InputEmpty` or
/// `ReadRecordResult::OutputFull` is returned, respectively. Similarly, if
/// the `ends` buffer is full, then `ReadRecordResult::OutputEndsFull` is
/// returned. See the documentation for `ReadRecordResult` for more
/// details.
///
/// The other three values correspond to the number of bytes read from
/// `input`, the number of bytes written to `output` and the number of
/// end positions written to `ends`, respectively.
///
/// The end positions written to `ends` are constructed as if there was
/// a single contiguous buffer in memory containing the entire row, even
/// if `ReadRecordResult::OutputFull` was returned in the middle of reading
/// a row.
///
/// # Termination
///
/// This reader interprets an empty `input` buffer as an indication that
/// there is no CSV data left to read. Namely, when the caller has
/// exhausted all CSV data, the caller should continue to call `read` with
/// an empty input buffer until `ReadRecordResult::End` is returned.
///
/// # Errors
///
/// This CSV reader can never return an error. Instead, it prefers *a*
/// parse over *no* parse.
pub fn read_record(
&mut self,
input: &[u8],
output: &mut [u8],
ends: &mut [usize],
) -> (ReadRecordResult, usize, usize, usize) {
let (input, bom_nin) = self.strip_utf8_bom(input);
let (res, nin, nout, nend) = if self.use_nfa {
self.read_record_nfa(input, output, ends)
} else {
self.read_record_dfa(input, output, ends)
};
self.has_read = true;
(res, nin + bom_nin, nout, nend)
}
/// Strip off a possible UTF-8 BOM at the start of a file. Quick note that
/// this method will fail to strip off the BOM if only part of the BOM is
/// buffered. Hopefully that won't happen very often.
fn strip_utf8_bom<'a>(&self, input: &'a [u8]) -> (&'a [u8], usize) {
let (input, nin) = if {
!self.has_read
&& input.len() >= 3
&& &input[0..3] == b"\xef\xbb\xbf"
} {
(&input[3..], 3)
} else {
(input, 0)
};
(input, nin)
}
#[inline(always)]
fn read_record_dfa(
&mut self,
input: &[u8],
output: &mut [u8],
ends: &mut [usize],
) -> (ReadRecordResult, usize, usize, usize) {
if input.is_empty() {
let s = self.transition_final_dfa(self.dfa_state);
let res =
self.dfa.new_read_record_result(s, true, false, false, false);
// This part is a little tricky. When reading the final record,
// the last result the caller will get is an InputEmpty, and while
// they'll have everything they need in `output`, they'll be
// missing the final end position of the final field in `ends`.
// We insert that here, but we must take care to handle the case
// where `ends` doesn't have enough space. If it doesn't have
// enough space, then we also can't transition to the next state.
return match res {
ReadRecordResult::Record => {
if ends.is_empty() {
return (ReadRecordResult::OutputEndsFull, 0, 0, 0);
}
self.dfa_state = s;
ends[0] = self.output_pos;
self.output_pos = 0;
(res, 0, 0, 1)
}
_ => {
self.dfa_state = s;
(res, 0, 0, 0)
}
};
}
if output.is_empty() {
return (ReadRecordResult::OutputFull, 0, 0, 0);
}
if ends.is_empty() {
return (ReadRecordResult::OutputEndsFull, 0, 0, 0);
}
let (mut nin, mut nout, mut nend) = (0, 0, 0);
let mut state = self.dfa_state;
while nin < input.len() && nout < output.len() && nend < ends.len() {
let (s, has_out) = self.dfa.get_output(state, input[nin]);
self.line += (input[nin] == b'\n') as u64;
state = s;
if has_out {
output[nout] = input[nin];
nout += 1;
}
nin += 1;
if state >= self.dfa.final_field {
ends[nend] = self.output_pos + nout;
nend += 1;
if state > self.dfa.final_field {
break;
}
}
if state == self.dfa.in_field || state == self.dfa.in_quoted {
self.dfa
.classes
.scan_and_copy(input, &mut nin, output, &mut nout);
}
}
let res = self.dfa.new_read_record_result(
state,
false,
nin >= input.len(),
nout >= output.len(),
nend >= ends.len(),
);
self.dfa_state = state;
if res.is_record() {
self.output_pos = 0;
} else {
self.output_pos += nout;
}
(res, nin, nout, nend)
}
#[inline(always)]
fn read_field_dfa(
&mut self,
input: &[u8],
output: &mut [u8],
) -> (ReadFieldResult, usize, usize) {
if input.is_empty() {
self.dfa_state = self.transition_final_dfa(self.dfa_state);
let res = self.dfa.new_read_field_result(
self.dfa_state,
true,
false,
false,
);
return (res, 0, 0);
}
if output.is_empty() {
return (ReadFieldResult::OutputFull, 0, 0);
}
let (mut nin, mut nout) = (0, 0);
let mut state = self.dfa_state;
while nin < input.len() && nout < output.len() {
let b = input[nin];
self.line += (b == b'\n') as u64;
let (s, has_out) = self.dfa.get_output(state, b);
state = s;
if has_out {
output[nout] = b;
nout += 1;
}
nin += 1;
if state >= self.dfa.final_field {
break;
}
}
let res = self.dfa.new_read_field_result(
state,
false,
nin >= input.len(),
nout >= output.len(),
);
self.dfa_state = state;
(res, nin, nout)
}
/// Perform the final state transition, i.e., when the caller indicates
/// that the input has been exhausted.
fn transition_final_dfa(&self, state: DfaState) -> DfaState {
// If we''ve already emitted a record or think we're ready to start
// parsing a new record, then we should sink into the final state
// and never move from there. (pro-tip: the start state doubles as
// the final state!)
if state >= self.dfa.final_record || state.is_start() {
self.dfa.new_state_final_end()
} else {
self.dfa.new_state_final_record()
}
}
/// Write the transition tables for the DFA based on this parser's
/// configuration.
fn build_dfa(&mut self) {
// A naive DFA transition table has
// `cells = (# number of states) * (# size of alphabet)`. While we
// could get away with that, the table would have `10 * 256 = 2560`
// entries. Even worse, in order to avoid a multiplication instruction
// when computing the next transition, we store the starting index of
// each state's row, which would not be representible in a single byte.
// So we'd need a `u16`, which doubles our transition table size to
// ~5KB. This is a lot to put on the stack, even though it probably
// fits in the L1 cache of most modern CPUs.
//
// To avoid this, we note that while our "true" alphabet
// has 256 distinct possibilities, the DFA itself is only
// discriminatory on a very small subset of that alphabet. For
// example, assuming neither `a` nor `b` are set as special
// quote/comment/escape/delimiter/terminator bytes, they are otherwise
// indistinguishable to the DFA, so it would be OK to treat them as
// if they were equivalent. That is, they are in the same equivalence
// class.
//
// As it turns out, using this logic, we can shrink our effective
// alphabet down to 7 equivalence classes:
//
// 1. The field delimiter.
// 2. The record terminator.
// 3. If the record terminator is CRLF, then CR and LF are
// distinct equivalence classes.
// 4. The quote byte.
// 5. The escape byte.
// 6. The comment byte.
// 7. Everything else.
//
// We add those equivalence classes here. If more configuration knobs
// are added to the parser with more discriminating bytes, then this
// logic will need to be adjusted further.
//
// Even though this requires an extra bit of indirection when computing
// the next transition, microbenchmarks say that it doesn't make much
// of a difference. Perhaps because everything fits into the L1 cache.
self.dfa.classes.add(self.delimiter);
if self.quoting {
self.dfa.classes.add(self.quote);
if let Some(escape) = self.escape {
self.dfa.classes.add(escape);
}
}
if let Some(comment) = self.comment {
self.dfa.classes.add(comment);
}
match self.term {
Terminator::Any(b) => self.dfa.classes.add(b),
Terminator::CRLF => {
self.dfa.classes.add(b'\r');
self.dfa.classes.add(b'\n');
}
_ => unreachable!(),
}
// Build the DFA transition table by computing the DFA state for all
// possible combinations of state and input byte.
for &state in NFA_STATES {
for c in (0..256).map(|c| c as u8) {
let mut nfa_result = (state, NfaInputAction::Epsilon);
// Consume NFA states until we hit a non-epsilon transition.
while nfa_result.0 != NfaState::End
&& nfa_result.1 == NfaInputAction::Epsilon
{
nfa_result = self.transition_nfa(nfa_result.0, c);
}
let from = self.dfa.new_state(state);
let to = self.dfa.new_state(nfa_result.0);
self.dfa.set(
from,
c,
to,
nfa_result.1 == NfaInputAction::CopyToOutput,
);
}
}
self.dfa_state = self.dfa.new_state(NfaState::StartRecord);
self.dfa.finish();
}
// The NFA implementation follows. The transition_final_nfa and
// transition_nfa methods are required for the DFA to operate. The
// rest are included for completeness (and debugging). Note that this
// NFA implementation is included in most of the CSV parser tests below.
#[inline(always)]
fn read_record_nfa(
&mut self,
input: &[u8],
output: &mut [u8],
ends: &mut [usize],
) -> (ReadRecordResult, usize, usize, usize) {
if input.is_empty() {
let s = self.transition_final_nfa(self.nfa_state);
let res = ReadRecordResult::from_nfa(s, false, false, false);
return match res {
ReadRecordResult::Record => {
if ends.is_empty() {
return (ReadRecordResult::OutputEndsFull, 0, 0, 0);
}
self.nfa_state = s;
ends[0] = self.output_pos;
self.output_pos = 0;
(res, 0, 0, 1)
}
_ => {
self.nfa_state = s;
(res, 0, 0, 0)
}
};
}
if output.is_empty() {
return (ReadRecordResult::OutputFull, 0, 0, 0);
}
if ends.is_empty() {
return (ReadRecordResult::OutputEndsFull, 0, 0, 0);
}
let (mut nin, mut nout, mut nend) = (0, self.output_pos, 0);
let mut state = self.nfa_state;
while nin < input.len() && nout < output.len() && nend < ends.len() {
let (s, io) = self.transition_nfa(state, input[nin]);
match io {
NfaInputAction::CopyToOutput => {
output[nout] = input[nin];
nout += 1;
nin += 1;
}
NfaInputAction::Discard => {
nin += 1;
}
NfaInputAction::Epsilon => {}
}
state = s;
if state.is_field_final() {
ends[nend] = nout;
nend += 1;
if state != NfaState::EndFieldDelim {
break;
}
}
}
let res = ReadRecordResult::from_nfa(
state,
nin >= input.len(),
nout >= output.len(),
nend >= ends.len(),
);
self.nfa_state = state;
self.output_pos = if res.is_record() { 0 } else { nout };
(res, nin, nout, nend)
}
#[inline(always)]
fn read_field_nfa(
&mut self,
input: &[u8],
output: &mut [u8],
) -> (ReadFieldResult, usize, usize) {
if input.is_empty() {
self.nfa_state = self.transition_final_nfa(self.nfa_state);
let res = ReadFieldResult::from_nfa(self.nfa_state, false, false);
return (res, 0, 0);
}
if output.is_empty() {
// If the output buffer is empty, then we can never make progress,
// so just quit now.
return (ReadFieldResult::OutputFull, 0, 0);
}
let (mut nin, mut nout) = (0, 0);
let mut state = self.nfa_state;
while nin < input.len() && nout < output.len() {
let (s, io) = self.transition_nfa(state, input[nin]);
match io {
NfaInputAction::CopyToOutput => {
output[nout] = input[nin];
nout += 1;
nin += 1;
}
NfaInputAction::Discard => {
nin += 1;
}
NfaInputAction::Epsilon => (),
}
state = s;
if state.is_field_final() {
break;
}
}
let res = ReadFieldResult::from_nfa(
state,
nin >= input.len(),
nout >= output.len(),
);
self.nfa_state = state;
(res, nin, nout)
}
/// Compute the final NFA transition after all caller-provided input has
/// been exhausted.
#[inline(always)]
fn transition_final_nfa(&self, state: NfaState) -> NfaState {
use self::NfaState::*;
match state {
End | StartRecord | EndRecord | InComment | CRLF => End,
StartField | EndFieldDelim | EndFieldTerm | InField
| InQuotedField | InEscapedQuote | InDoubleEscapedQuote
| InRecordTerm => EndRecord,
}
}
/// Compute the next NFA state given the current NFA state and the current
/// input byte.
///
/// This returns the next NFA state along with an NfaInputAction that
/// indicates what should be done with the input byte (nothing for an epsilon
/// transition, copied to a caller provided output buffer, or discarded).
#[inline(always)]
fn transition_nfa(
&self,
state: NfaState,
c: u8,
) -> (NfaState, NfaInputAction) {
use self::NfaState::*;
match state {
End => (End, NfaInputAction::Epsilon),
StartRecord => {
if self.term.equals(c) {
(StartRecord, NfaInputAction::Discard)
} else if self.comment == Some(c) {
(InComment, NfaInputAction::Discard)
} else {
(StartField, NfaInputAction::Epsilon)
}