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
use std::io::Read;
use std::path::Path;

use crate::config::Config;
use crate::parser::output::Output;
use crate::scheduler::Scheduler;

/// Marker type: fields are handed to the callback as a fixed-size array `[&mut T; N]` (default).
pub struct Arity;

/// Marker type: fields are handed to the callback as a slice `&mut [&mut T]`.
pub struct Variadic;

/// Fields are validated as UTF-8 and handed out as `&mut str` (default).
pub type Text = str;

/// Fields are raw bytes, no UTF-8 validation. For non-UTF-8 encodings.
pub type Bytes = [u8];

/// The CSV parser, parameterized by field count mode and encoding.
pub struct Parser<Mode = Arity, Encoding: ?Sized = Text> {
    config: Config,
    _marker: std::marker::PhantomData<(Mode, Encoding)>,
}

impl Default for Parser<Arity, Text> {
    fn default() -> Self {
        Self::new()
    }
}

/// Construct a parser from a `Config`, validating it first.
pub(crate) fn try_from_config<Mode, Encoding: Output + ?Sized>(
    config: Config,
) -> crate::Result<Parser<Mode, Encoding>> {
    config.validate()?;
    if Encoding::REQUIRES_ASCII_CONTROL_BYTES {
        config.validate_ascii_control_bytes()?;
    }
    Ok(Parser {
        config,
        _marker: std::marker::PhantomData,
    })
}

impl Parser<Arity, Text> {
    /// Construct a parser with default settings.
    ///
    /// The default config is statically known to be valid, so this
    /// is infallible. Use `ParserBuilder` for custom settings.
    pub fn new() -> Self {
        try_from_config(Config::default()).expect("default config must validate")
    }

    /// Parse a CSV file with a fixed number of fields per record.
    ///
    /// The file is split into chunks and parsed in parallel. `N` is
    /// inferred from the closure and validated at runtime.
    ///
    /// ```ignore
    /// parser.parse("data.csv", init, acc, merge)
    /// ```
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse<P, S, I, A, M, R, const N: usize>(
        &mut self,
        path: P,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        P: AsRef<Path>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, [&mut str; N]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        let acc_slice = move |state: &mut S, fields: &mut [&mut str]| {
            acc(state, fields_as_array::<_, N>(fields))
        };
        parse(
            self.arity_config::<N>(),
            path.as_ref(),
            init,
            acc_slice,
            merge,
        )
    }

    /// Parse CSV from any reader with a fixed number of fields per record.
    ///
    /// Sequential and single-threaded — for inputs without random access
    /// (stdin, pipes, sockets, decompressors). Prefer [`Self::parse`] for
    /// files on disk, which parses in parallel.
    /// No speculation, so the accumulator sees every record exactly once.
    ///
    /// Do not wrap `reader` in a `BufReader`: the parser reads into its own
    /// ring buffer in large blocks, so an intermediate buffer only adds a copy.
    ///
    /// ```ignore
    /// parser.parse_stream(std::io::stdin().lock(), init, acc, merge)
    /// ```
    pub fn parse_stream<Rd, S, I, A, M, R, const N: usize>(
        &mut self,
        reader: Rd,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        Rd: Read,
        I: FnOnce() -> S,
        A: Fn(&mut S, [&mut str; N]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>,
        M: FnOnce(&mut [S]) -> R,
    {
        let acc_slice = move |state: &mut S, fields: &mut [&mut str]| {
            acc(state, fields_as_array::<_, N>(fields))
        };
        parse_stream(self.arity_config::<N>(), reader, init, acc_slice, merge)
    }

    /// Parse CSV already in memory, with a fixed number of fields per record.
    ///
    /// Chunked and parsed in parallel like [`Self::parse`]. Accepts anything
    /// that derefs to bytes — `&[u8]`, `Vec<u8>`, `&str`, `String`:
    ///
    /// ```ignore
    /// parser.parse_slice("name,age\nada,36\n", init, acc, merge)
    /// ```
    ///
    /// The parser writes into the buffer it parses, so the bytes are copied
    /// into thread-private buffers rather than parsed in place; `data` itself
    /// is never modified.
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse_slice<D, S, I, A, M, R, const N: usize>(
        &mut self,
        data: D,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        D: AsRef<[u8]>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, [&mut str; N]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        let acc_slice = move |state: &mut S, fields: &mut [&mut str]| {
            acc(state, fields_as_array::<_, N>(fields))
        };
        parse_slice(
            self.arity_config::<N>(),
            data.as_ref(),
            init,
            acc_slice,
            merge,
        )
    }

    /// Clone the config, pinning the field count to the callback's arity.
    fn arity_config<const N: usize>(&self) -> Config {
        let mut config = self.config.clone();
        config.field_count = Some(N);
        config
    }
}

impl Parser<Variadic, Text> {
    /// Parse a CSV file with a variable number of fields per record.
    ///
    /// The file is split into chunks and parsed in parallel.
    ///
    /// ```ignore
    /// parser.parse("data.csv", init, acc, merge)
    /// ```
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse<P, S, I, A, M, R>(
        &mut self,
        path: P,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        P: AsRef<Path>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, &mut [&mut str]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
            + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        parse(self.config.clone(), path.as_ref(), init, acc, merge)
    }

    /// Parse CSV from any reader with a variable number of fields per record.
    ///
    /// Sequential and single-threaded — see [`Parser::parse_stream`] for when
    /// to reach for this over [`Self::parse`].
    pub fn parse_stream<Rd, S, I, A, M, R>(
        &mut self,
        reader: Rd,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        Rd: Read,
        I: FnOnce() -> S,
        A: Fn(&mut S, &mut [&mut str]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>,
        M: FnOnce(&mut [S]) -> R,
    {
        parse_stream(self.config.clone(), reader, init, acc, merge)
    }

    /// Parse CSV already in memory, with a variable number of fields per
    /// record. Chunked and parsed in parallel like [`Self::parse`]; see
    /// [`Parser::parse_slice`] for what `data` may be.
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse_slice<D, S, I, A, M, R>(
        &mut self,
        data: D,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        D: AsRef<[u8]>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, &mut [&mut str]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
            + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        parse_slice(self.config.clone(), data.as_ref(), init, acc, merge)
    }
}

impl Parser<Arity, Bytes> {
    /// Parse a CSV file with a fixed number of raw byte fields per record.
    ///
    /// The file is split into chunks and parsed in parallel.
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse<P, S, I, A, M, R, const N: usize>(
        &mut self,
        path: P,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        P: AsRef<Path>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, [&mut [u8]; N]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
            + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        let acc_slice = move |state: &mut S, fields: &mut [&mut [u8]]| {
            acc(state, fields_as_array::<_, N>(fields))
        };
        parse(
            self.arity_config::<N>(),
            path.as_ref(),
            init,
            acc_slice,
            merge,
        )
    }

    /// Parse raw byte fields from any reader, fixed field count per record.
    ///
    /// Sequential and single-threaded — see [`Parser::parse_stream`] for when
    /// to reach for this over [`Self::parse`].
    pub fn parse_stream<Rd, S, I, A, M, R, const N: usize>(
        &mut self,
        reader: Rd,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        Rd: Read,
        I: FnOnce() -> S,
        A: Fn(&mut S, [&mut [u8]; N]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>,
        M: FnOnce(&mut [S]) -> R,
    {
        let acc_slice = move |state: &mut S, fields: &mut [&mut [u8]]| {
            acc(state, fields_as_array::<_, N>(fields))
        };
        parse_stream(self.arity_config::<N>(), reader, init, acc_slice, merge)
    }

    /// Parse in-memory CSV as raw byte fields, fixed field count per record.
    ///
    /// Chunked and parsed in parallel like [`Self::parse`]; see
    /// [`Parser::parse_slice`] for what `data` may be.
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse_slice<D, S, I, A, M, R, const N: usize>(
        &mut self,
        data: D,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        D: AsRef<[u8]>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, [&mut [u8]; N]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
            + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        let acc_slice = move |state: &mut S, fields: &mut [&mut [u8]]| {
            acc(state, fields_as_array::<_, N>(fields))
        };
        parse_slice(
            self.arity_config::<N>(),
            data.as_ref(),
            init,
            acc_slice,
            merge,
        )
    }

    /// Clone the config, pinning the field count to the callback's arity.
    fn arity_config<const N: usize>(&self) -> Config {
        let mut config = self.config.clone();
        config.field_count = Some(N);
        config
    }
}

impl Parser<Variadic, Bytes> {
    /// Parse a CSV file with a variable number of raw byte fields per record.
    ///
    /// The file is split into chunks and parsed in parallel.
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse<P, S, I, A, M, R>(
        &mut self,
        path: P,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        P: AsRef<Path>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, &mut [&mut [u8]]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
            + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        parse(self.config.clone(), path.as_ref(), init, acc, merge)
    }

    /// Parse raw byte fields from any reader, variable field count per record.
    ///
    /// Sequential and single-threaded — see [`Parser::parse_stream`] for when
    /// to reach for this over [`Self::parse`].
    pub fn parse_stream<Rd, S, I, A, M, R>(
        &mut self,
        reader: Rd,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        Rd: Read,
        I: FnOnce() -> S,
        A: Fn(&mut S, &mut [&mut [u8]]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>,
        M: FnOnce(&mut [S]) -> R,
    {
        parse_stream(self.config.clone(), reader, init, acc, merge)
    }

    /// Parse in-memory CSV as raw byte fields, variable field count per
    /// record. Chunked and parsed in parallel like [`Self::parse`]; see
    /// [`Parser::parse_slice`] for what `data` may be.
    ///
    /// The accumulator also runs on records from speculative passes that
    /// turn out wrong — see [side effects](crate#side-effects).
    pub fn parse_slice<D, S, I, A, M, R>(
        &mut self,
        data: D,
        init: I,
        acc: A,
        merge: M,
    ) -> crate::Result<R>
    where
        D: AsRef<[u8]>,
        S: Send,
        I: Fn() -> S + Sync,
        A: Fn(&mut S, &mut [&mut [u8]]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
            + Sync,
        M: FnOnce(&mut [S]) -> R,
    {
        parse_slice(self.config.clone(), data.as_ref(), init, acc, merge)
    }
}

/// Run the parallel (chunked, file-backed) pipeline against `path`.
#[cfg_attr(feature = "trace", tracing::instrument(skip(init, acc, merge)))]
fn parse<S, I, A, M, R, O>(
    config: Config,
    path: &Path,
    init: I,
    acc: A,
    merge: M,
) -> crate::Result<R>
where
    S: Send,
    I: Fn() -> S + Sync,
    A: Fn(&mut S, &mut [&mut O]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> + Sync,
    M: FnOnce(&mut [S]) -> R,
    O: Output + ?Sized,
{
    Scheduler::new(config).run(path, init, acc, merge)
}

/// Run the parallel (chunked, in-memory) pipeline against `data`.
#[cfg_attr(feature = "trace", tracing::instrument(skip(init, acc, merge)))]
fn parse_slice<S, I, A, M, R, O>(
    config: Config,
    data: &[u8],
    init: I,
    acc: A,
    merge: M,
) -> crate::Result<R>
where
    S: Send,
    I: Fn() -> S + Sync,
    A: Fn(&mut S, &mut [&mut O]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> + Sync,
    M: FnOnce(&mut [S]) -> R,
    O: Output + ?Sized,
{
    Scheduler::new(config).run_slice(data, init, acc, merge)
}

/// Run the sequential single-threaded pipeline against `reader`.
///
/// Unlike [`parse`] this never crosses a thread boundary, so the
/// callbacks need neither `Send` nor `Sync`.
#[cfg_attr(feature = "trace", tracing::instrument(skip(reader, init, acc, merge)))]
fn parse_stream<Rd, S, I, A, M, R, O>(
    config: Config,
    reader: Rd,
    init: I,
    acc: A,
    merge: M,
) -> crate::Result<R>
where
    Rd: Read,
    I: FnOnce() -> S,
    A: Fn(&mut S, &mut [&mut O]) -> Result<(), Box<dyn std::error::Error + Send + Sync>>,
    M: FnOnce(&mut [S]) -> R,
    O: Output + ?Sized,
{
    Scheduler::new(config).run_stream(reader, init, acc, merge)
}

/// Reborrow a slice of fields as a fixed-size array of reborrowed fields.
fn fields_as_array<'a, T: ?Sized, const N: usize>(fields: &'a mut [&mut T]) -> [&'a mut T; N] {
    assert_eq!(fields.len(), N, "record arity not verified by the parser");
    let mut fields = fields.iter_mut();
    std::array::from_fn(|_| &mut **fields.next().unwrap())
}