csveee 0.2.1

A very fast, parallel CSV parser.
Documentation
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
//! SIMD-flavored `find_record_start`: scans a chunk under a CSV-semantic
//! [`Assumption`] for the first `(N & D_struct)` bit, and under `strict`
//! rejects a quote that contradicts it — see [`StrictProbe`].

use super::bitmask::{Structural, VECTOR_BYTES, compute_in_quotes, match_structural, neutral_pad};
use super::isa::Isa;
use crate::config::Config;
use crate::io::ChunkReader;
use crate::parser::chunk::Assumption;

/// Initial in-quotes carry for the M-bitmask: the M-state of the byte
/// just before the chunk. Mid-escape, a doubled quote has already
/// toggled M back out, so only a distinct escape byte carries `true`.
fn initial_carry(config: &Config, assumption: Assumption) -> bool {
    match assumption {
        Assumption::OutOfQuotes => false,
        Assumption::InQuotes => true,
        Assumption::InQuotesAfterEscape => config.quote != config.escape,
    }
}

/// Scan forward under `assumption` for the first out-of-quotes record
/// terminator, consuming the bytes before it and returning its offset,
/// relative to the reader's position. `None` if the chunk has none.
pub(super) fn find_record_start<R: ChunkReader, I: Isa>(
    isa: I,
    reader: &mut R,
    config: &Config,
    assumption: Assumption,
    strict: bool,
) -> crate::Result<Option<usize>> {
    let (term, term_b) = config.terminator.bytes();
    let delim = config.delimiter;
    let quote = config.quote;
    let pad = neutral_pad(delim, term, term_b, quote);

    let mut carry = initial_carry(config, assumption);
    let mut total_consumed: usize = 0;
    let mut probe = StrictProbe::new();

    loop {
        // Near EOF `buffer()` is shorter; the `scan_end` cap covers that.
        reader.fill(VECTOR_BYTES)?;
        let buf = reader.buffer();
        if buf.is_empty() {
            return Ok(None);
        }

        let chunk_end = reader.remaining_in_chunk();
        if chunk_end == 0 {
            return Ok(None);
        }

        // Never read past the chunk boundary; the merge phase reparses a
        // record that straddles chunks.
        let scan_end = chunk_end.min(buf.len());
        let avail = scan_end.min(VECTOR_BYTES);

        // The neutral pad produces no structural bits, so any terminator
        // found sits at a real input position.
        let v: [u8; VECTOR_BYTES] = if avail == VECTOR_BYTES {
            buf[..VECTOR_BYTES].try_into().expect("64-byte slice")
        } else {
            let mut padded = [pad; VECTOR_BYTES];
            padded[..avail].copy_from_slice(&buf[..avail]);
            padded
        };

        let s = match_structural(isa, &v, delim, term, term_b, quote);
        let (m, new_carry) = compute_in_quotes(isa, s.quote, carry);
        let d_struct = s.structural_delims(m);
        let structural_term = s.term & d_struct;

        // First out-of-quotes terminator within the real (non-pad) bytes.
        let term_bit = (structural_term != 0)
            .then(|| structural_term.trailing_zeros() as usize)
            .filter(|&b| b < avail);

        if strict && let Some(e) = probe.check(&s, m, avail, term_bit, total_consumed) {
            return Err(e);
        }

        if let Some(bit) = term_bit {
            reader.consume(bit);
            return Ok(Some(total_consumed + bit));
        }

        if avail < VECTOR_BYTES {
            // Tail vector with no terminator: the merge path takes over.
            return Ok(None);
        }

        carry = new_carry;
        if strict {
            probe.advance(&s);
        }
        reader.consume(VECTOR_BYTES);
        total_consumed += VECTOR_BYTES;
    }
}

/// Strict-probe error at a chunk-relative offset; the scheduler rebases
/// it via `Error::with_base`.
fn strict_err(byte_offset: usize) -> crate::Error {
    crate::Error::InvalidQuote {
        position: crate::error::Position { byte_offset },
    }
}

/// Cross-vector state for the strict probe: the two neighbour bits that
/// straddle 64-byte vectors.
struct StrictProbe {
    /// Whether the previous vector's last real byte was a field boundary.
    prev_last_bnd: bool,
    /// A closing quote parked in bit 63, with the chunk-relative offset
    /// of the byte that has to follow it.
    pending_closer_msb: Option<usize>,
}

impl StrictProbe {
    fn new() -> Self {
        Self {
            prev_last_bnd: true,
            pending_closer_msb: None,
        }
    }

    /// Inspect one vector, returning `Some(err)` if it proves the assumed
    /// in-quotes state impossible: an opener without a preceding boundary,
    /// or a closer without a following one (`""` pairs count as one).
    fn check(
        &mut self,
        s: &Structural,
        m: u64,
        avail: usize,
        term_bit: Option<usize>,
        total_consumed: usize,
    ) -> Option<crate::Error> {
        let bnd = s.delim | s.term | s.quote;

        // Resolve a deferred bit-63 closer against this vector's byte 0.
        if let Some(pos) = self.pending_closer_msb.take()
            && bnd & 1 == 0
        {
            return Some(strict_err(pos));
        }

        let openers = s.quote & m;
        let closers = s.quote & !m;
        let left_bnd = (bnd << 1) | self.prev_last_bnd as u64;
        let right_bnd = bnd >> 1;
        let bad_openers = openers & !left_bnd;
        let mut bad_closers = closers & !right_bnd;

        // A bit-63 closer's right neighbour is in the next vector.
        const MSB: u64 = 1 << 63;
        if avail == VECTOR_BYTES && bad_closers & MSB != 0 {
            bad_closers &= !MSB;
            self.pending_closer_msb = Some(total_consumed + VECTOR_BYTES);
        }
        // A tail vector's last byte borders the chunk/EOF edge.
        if avail < VECTOR_BYTES && avail > 0 {
            bad_closers &= !(1u64 << (avail - 1));
        }

        // Bad bits past the terminator belong to the next record.
        let cutoff = term_bit.unwrap_or(avail);
        let mask_below = if cutoff >= 64 {
            u64::MAX
        } else {
            (1u64 << cutoff) - 1
        };
        let bad_openers = bad_openers & mask_below;
        let bad_closers = bad_closers & mask_below;

        let opener = (bad_openers != 0).then(|| bad_openers.trailing_zeros() as usize);
        // Like the DFA, anchor a misplaced closer on the byte after it.
        let closer = (bad_closers != 0).then(|| bad_closers.trailing_zeros() as usize + 1);
        Some(strict_err(
            total_consumed + opener.into_iter().chain(closer).min()?,
        ))
    }

    /// Carry the last byte forward as the next vector's left neighbour.
    fn advance(&mut self, s: &Structural) {
        self.prev_last_bnd = (s.delim | s.term | s.quote) >> 63 != 0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Config, RecordTerminator};
    use crate::parser::simd::isa::CompileTime;

    /// In-memory `ChunkReader` for tests.
    struct VecReader {
        /// The whole input.
        data: Vec<u8>,
        /// Read cursor into `data`.
        pos: usize,
        /// Simulated chunk boundary, as an offset into `data`.
        chunk_end: usize,
    }

    impl VecReader {
        fn new(data: &[u8], chunk_end: usize) -> Self {
            Self {
                data: data.to_vec(),
                pos: 0,
                chunk_end,
            }
        }
    }

    impl ChunkReader for VecReader {
        fn buffer(&self) -> &[u8] {
            &self.data[self.pos..]
        }
        fn buffer_mut(&mut self) -> &mut [u8] {
            &mut self.data[self.pos..]
        }
        fn fill(&mut self, _n: usize) -> std::io::Result<()> {
            Ok(())
        }
        fn consume(&mut self, n: usize) {
            self.pos += n;
        }
        fn remaining_in_chunk(&self) -> usize {
            self.chunk_end.saturating_sub(self.pos)
        }
    }

    fn lf_config() -> Config {
        let mut c = Config::default();
        c.terminator = RecordTerminator::LF;
        c
    }

    #[test]
    fn out_of_quotes_finds_first_terminator() {
        // "field_a,field_b\nrecord2\n" — first \n at byte 15.
        let data = b"field_a,field_b\nrecord2\n";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(15));
    }

    #[test]
    fn in_quotes_finds_first_terminator_after_close() {
        // `inside",field\nrec2\n`: the closer is at 6, so the first
        // out-of-quotes \n is at 13.
        let data = b"inside\",field\nrec2\n";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::InQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(13));
    }

    #[test]
    fn in_quotes_ignores_terminator_inside_quotes() {
        // The `\n` at byte 6 is inside the quoted field.
        let data = b"inside\nstill\",x\nrec2\n";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::InQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(15));
    }

    #[test]
    fn returns_none_when_no_terminator_in_chunk() {
        // No \n at all → None.
        let data = b"a,b,c";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, None);
    }

    #[test]
    fn respects_chunk_boundary() {
        // The terminator at byte 30 is past chunk_end = 20.
        let mut data = vec![b'a'; 30];
        data.push(b'\n');
        data.extend_from_slice(b"rec2\n");
        let mut r = VecReader::new(&data, 20);
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, None);
        // The reader must not have consumed past the chunk end.
        assert!(r.pos <= 20);
    }

    #[test]
    fn terminator_in_second_vector() {
        // Pad with non-structural content for 70 bytes, then a \n.
        let mut data = vec![b'a'; 70];
        data.push(b'\n');
        data.extend_from_slice(b"rec\n");
        let mut r = VecReader::new(&data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(70));
    }

    #[test]
    fn terminator_at_vector_boundary() {
        // \n at exactly byte 63 (last byte of the first vector).
        let mut data = vec![b'a'; 63];
        data.push(b'\n');
        data.extend_from_slice(b"rec\n");
        let mut r = VecReader::new(&data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(63));
    }

    #[test]
    fn quoted_terminator_then_real_one() {
        // `"a\nb",x\ny`: the \n at byte 2 is quoted, the one at 7 is
        // structural.
        let data = b"\"a\nb\",x\ny";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(7));
    }

    #[test]
    fn in_quotes_after_escape_treats_carry_as_out_of_quotes() {
        // Byte 0 is the second `"` of a `""` pair, so the toggle puts us
        // back inside quotes and the first out-of-quotes `\n` is at 8.
        let data = b"\"more\",x\n";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::InQuotesAfterEscape,
            false,
        )
        .unwrap();
        assert_eq!(start, Some(8));
    }

    #[test]
    fn empty_input_returns_none() {
        let mut r = VecReader::new(b"", 0);
        let start = find_record_start(
            CompileTime,
            &mut r,
            &lf_config(),
            Assumption::OutOfQuotes,
            false,
        )
        .unwrap();
        assert_eq!(start, None);
    }

    #[test]
    fn semicolon_delimiter() {
        // Sanity: non-default delimiters work.
        let mut c = lf_config();
        c.delimiter = b';';
        let data = b"a;b;c\nrec2\n";
        let mut r = VecReader::new(data, data.len());
        let start =
            find_record_start(CompileTime, &mut r, &c, Assumption::OutOfQuotes, false).unwrap();
        assert_eq!(start, Some(5));
    }

    // ── strict probe ─────────────────────────────────────────────────

    /// Config with a quote char so the strict probe is meaningful.
    fn quoted_lf_config() -> Config {
        let mut c = lf_config();
        c.quote = Some(b'"');
        c
    }

    #[test]
    fn strict_rejects_wrong_out_of_quotes_assumption() {
        // The chunk starts inside a quoted field, so under `OutOfQuotes`
        // the closer looks like an opener preceded by content (`l"`).
        let data = b"g-gu, Seoul\",37\nnext,rec\n";
        let mut r = VecReader::new(data, data.len());
        let err = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::OutOfQuotes,
            true,
        );
        assert!(
            matches!(err, Err(crate::Error::InvalidQuote { .. })),
            "got {err:?}"
        );
    }

    #[test]
    fn strict_accepts_correct_in_quotes_assumption() {
        // Correct assumption: the `"` is a closer followed by `,`.
        let data = b"g-gu, Seoul\",37\nnext,rec\n";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::InQuotes,
            true,
        )
        .unwrap();
        assert_eq!(start, Some(15));
    }

    #[test]
    fn strict_accepts_well_formed_out_of_quotes() {
        // A properly-quoted middle field: opener after `,`, closer before.
        let data = b"a,\"b,c\",d\nrec2\n";
        let mut r = VecReader::new(data, data.len());
        let start = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::OutOfQuotes,
            true,
        )
        .unwrap();
        assert_eq!(start, Some(9));
    }

    #[test]
    fn strict_accepts_doubled_quote_escape() {
        // In a `""` pair each `"` is the other's legal neighbour.
        let data = b"a,\"x\"\"y\",b\nr2\n";
        let mut r = VecReader::new(data, data.len());
        let mut c = quoted_lf_config();
        c.escape = Some(b'"');
        let start =
            find_record_start(CompileTime, &mut r, &c, Assumption::OutOfQuotes, true).unwrap();
        assert_eq!(start, Some(10));
    }

    /// A misplaced closer is anchored on the byte that follows it, as the
    /// DFA probe anchors it.
    #[test]
    fn strict_closer_error_anchors_on_following_byte() {
        // Under `InQuotes` the `"` at 3 closes, but `d` is no boundary.
        let data = b"abc\"def,x\n";
        let mut r = VecReader::new(data, data.len());
        let err = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::InQuotes,
            true,
        );
        assert!(
            matches!(
                err,
                Err(crate::Error::InvalidQuote {
                    position: crate::error::Position { byte_offset: 4 }
                })
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn strict_opener_error_anchors_on_the_quote() {
        // Under `OutOfQuotes` the `"` at 11 opens, but `l` is no boundary.
        let data = b"g-gu, Seoul\",37\nnext,rec\n";
        let mut r = VecReader::new(data, data.len());
        let err = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::OutOfQuotes,
            true,
        );
        assert!(
            matches!(
                err,
                Err(crate::Error::InvalidQuote {
                    position: crate::error::Position { byte_offset: 11 }
                })
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn strict_closer_at_bit_63_anchors_on_next_vector() {
        // The closer sits in bit 63, so its right neighbour — byte 64 of
        // the next vector — decides, and carries the offset.
        let mut data = vec![b'a'; 63];
        data.push(b'"');
        data.extend_from_slice(b"x,y\n");
        let mut r = VecReader::new(&data, data.len());
        let err = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::InQuotes,
            true,
        );
        assert!(
            matches!(
                err,
                Err(crate::Error::InvalidQuote {
                    position: crate::error::Position { byte_offset: 64 }
                })
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn strict_rejects_across_vector_boundary() {
        // A contradicting quote past the first vector: the carry must see it.
        let mut data = vec![b'a'; 70];
        data.extend_from_slice(b" text\",99\nnext\n");
        let mut r = VecReader::new(&data, data.len());
        let err = find_record_start(
            CompileTime,
            &mut r,
            &quoted_lf_config(),
            Assumption::OutOfQuotes,
            true,
        );
        assert!(
            matches!(err, Err(crate::Error::InvalidQuote { .. })),
            "got {err:?}"
        );
    }
}