simd_csv/
lib.rs

1/*!
2The `simd-csv` crate provides specialized readers & writers of CSV data able
3to leverage [SIMD](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) instructions.
4
5It has been designed to fit the [xan](https://github.com/medialab/xan) command line tool's
6requirements, but can be used by anyone to speed up CSV parsing.
7
8Is is less flexible and user-friendly than the [`csv`](https://docs.rs/csv/) crate,
9so one should make sure the performance gain is worth it before going further.
10
11This crate is not a port of [simdjson](https://arxiv.org/abs/1902.08318) branchless logic
12applied to CSV parsing. It uses a somewhat novel approach instead, mixing traditional state
13machine logic with [`memchr`](https://docs.rs/memchr/latest/memchr/)-like SIMD-accelerated
14string searching. See the [design notes](#design-notes) for more details.
15
16# Examples
17
18*Reading a CSV file while amortizing allocations*
19
20```
21use std::fs::File;
22use simd_csv::{Reader, ByteRecord};
23
24let mut reader = Reader::from_reader(File::open("data.csv")?);
25let mut record = ByteRecord::new();
26
27while reader.read_byte_record(&mut record)? {
28    for cell in record.iter() {
29        dbg!(cell);
30    }
31}
32```
33
34*Using a builder to configure your reader*
35
36```
37use std::fs::File;
38use simd_csv::ReaderBuilder;
39
40let mut reader = ReaderBuilder::new()
41    .delimiter(b'\t')
42    .buffer_capacity(16 * (1 << 10))
43    .from_reader(File::open("data.csv")?);
44```
45
46*Using the zero-copy reader*
47
48```
49use std::fs::File;
50use simd_csv::ZeroCopyReader;
51
52let mut reader = ZeroCopyReader::from_reader(File::new("data.csv")?);
53
54while let Some(record) = reader.read_byte_record()? {
55    // Only unescaping third column:
56    dbg!(record.unescape(2));
57}
58```
59
60*Counting records as fast as possible using the splitter*
61
62```
63use std::fs::File;
64use simd_csv::Splitter;
65
66let mut splitter = Splitter::from_reader(File::new("data.csv")?);
67
68println!("{}", splitter.count_records()?);
69```
70
71# Readers
72
73From least to most performant. Also from most integrated to most barebone.
74
75- [`Reader`], [`ReaderBuilder`]: a streaming copy reader, unescaping quoted data on the fly.
76  This is the closest thing you will find to the [`csv`](https://docs.rs/csv/) crate `Reader`.
77- [`ZeroCopyReader`], [`ZeroCopyReaderBuilder`]: a streaming zero-copy reader that only find cell
78  delimiters and does not unescape quoted data.
79- [`Splitter`], [`SplitterBuilder`]: a streaming zero-copy splitter that will only
80  find record delimitations, but not cell delimiters at all.
81- [`LineReader`]: a streaming zero-copy line splitter that does not handle quoting at all.
82
83You can also find more exotic readers like:
84
85- [`TotalReader`], [`TotalReaderBuilder`]: a reader optimized to work with uses-cases when
86  CSV data is fully loaded into memory or with memory maps.
87- [`Seeker`], [`SeekerBuilder`]: a reader able to find record start positions in a seekable CSV stream.
88  This can be very useful for parallelization, or more creative uses like performing binary
89  search in a sorted file.
90- [`ReverseReader`], [`ReaderBuilder`]: a reader able to read a seekable CSV stream in reverse, in amortized linear time.
91
92# Writers
93
94- [`Writer`], [`WriterBuilder`]: a typical CSV writer.
95
96# Supported targets
97
98- On `x86_64` targets, `sse2` instructions are used. `avx2` instructions
99  will also be used if their availability is detected at runtime.
100- On `aarch64` targets, `neon` instructions are used.
101- On `wasm` targets, `simd128` instructions are used.
102- Everywhere else, the library will fallback to [SWAR](https://en.wikipedia.org/wiki/SWAR)
103  techniques or scalar implementations.
104
105Using `RUSTFLAGS='-C target-cpu=native'` should not be required when compiling
106this crate because it either uses SIMD instructions tied to your `target_arch`
107already and because it will rely on runtime detection to find better SIMD
108instructions (typically `avx2`).
109
110# Design notes
111
112## Regarding performance
113
114This crate's CSV parser has been cautiously designed to offer "reasonable" performance
115by combinining traditional state machine logic with SIMD-accelerated string searching.
116
117I say "reasonable" because you cannot expect to parse 16/32 times faster than a state-of-the-art
118scalar implementation like the [`csv`](https://docs.rs/csv/) crate. What's more, the
119throughput of the SIMD-accelerated parser remains very data-dependent. Sometimes
120you will go up to ~8 times faster, sometimes you will only go as fast as scalar code.
121(Remember also that CSV parsing is often an IO-bound task, even more so than with other
122data formats expected to fit into memory like JSON etc.)
123
124As a rule of thumb, the larger your records and cells, the greater the
125performance boost vs. a scalar byte-by-byte implementation will be. This also means that
126for worst cases, this crate's parser will just be on par with scalar code. I
127have made everything in my power to ensure this SIMD parser is never slower (I think
128one of the reasons why SIMD CSV parsers are not yet very prevalent is that they
129tend to suffer real-life cases where scalar code outperform them).
130
131Also, note that this crate is geared towards parsing **streams** of CSV data
132only quoted when needed (e.g. not written with a `QUOTE_ALWAYS` policy).
133
134## Regarding simdjson techniques
135
136I have tried very hard to apply [simdjson](https://arxiv.org/abs/1902.08318) tricks
137to make this crate's parser as branchless as possible but I couldn't make it as
138fast as the state-machine/SIMD string searching hybrid.
139
140`PCLMULQDQ` & shuffling tricks in this context only add more complexity and overhead
141to the SIMD sections of the code, all while making it less "democratic" since you need
142specific SIMD instructions that are not available everywhere, if you don't want to
143fallback to scalar instructions.
144
145Said differently, those techniques seem overkill in practice for CSV parsing.
146But it is also possible I am not competent enough to make them work properly and
147I won't hesitate to move towards them if proven wrong.
148
149## Hybrid design
150
151This crate's CSV parser follows a hybrid approach where we maintain a traditional
152state machine, but search for structural characters in the byte stream using
153SIMD string searching techniques like the ones implemented in the excellent
154[`memchr`](https://docs.rs/memchr/latest/memchr/) crate:
155
156The idea is to compare 16/32 bytes of data at once with splats of structural
157characters like `\n`, `"` or `,` in order to extract a "move mask" that will
158be handled as a bit string so we can find whether and where some character
159was found using typical bit-twiddling.
160
161This ultimately means that branching happens on each structural characters rather
162than on each byte, which is very good. But this is also the reason why CSV data
163with a very high density of structural characters will not get parsed much faster
164than with the equivalent scalar code.
165
166## Two-speed SIMD branches
167
168This crate's CSV parser actually uses two different modes of SIMD string searching:
169
1701. when reading unquoted CSV data, the parser uses an amortized variant of the
171   [`memchr`](https://docs.rs/memchr/latest/memchr/) routines where move masks
172   containing more than a single match are kept and consumed progressively on subsequent calls,
173   instead of restarting a search from the character just next to an earlier match, as the
174   `memchr_iter` routine does.
1752. when reading quoted CSV data, the parser uses the optmized & unrolled functions
176   of the [`memchr`](https://docs.rs/memchr/latest/memchr/) crate directly to find the next
177   quote as fast as possible.
178
179This might seem weird but this seems to be the best tradeoff for performance. Counter-intuitively,
180using larger SIMD registers like `avx2` for 1. actually hurts the overall performance.
181Similarly, using the amortized routine to scan quoted data is actually slower than
182using the unrolled functions of [`memchr`](https://docs.rs/memchr/latest/memchr/).
183
184This actually makes sense if you consider that the longer a field is, the more
185probable it is to contain a character requiring the field to be quoted. What's more
186the density of quotes to be found in a quoted field is usually lower that structural
187characters in an unquoted CSV stream. So if you use larger SIMD registers in the
188unquoted stream you will end up 1. throttling the SIMD part of the code too much
189because of the inner branching (when hitting a delimiter or a newline) and 2. you
190will often discard too much work when hitting a record end or a quoted field.
191
192## Copy amortization
193
194Copying tiny amounts of data often is quite detrimental to the overall performance.
195As such, and to make sure the copying [`Reader`] remains as fast as possible,
196I decided to change the design of the [`ByteRecord`] to save fields as fully-fledged
197ranges over the underlying byte slice instead of only delimiting them implicitly
198by the offsets separating them as it is done in the [`csv`](https://docs.rs/csv/) crate.
199
200This means I am able to copy large swathes of unquoted data at once instead of
201copying fields one by one. This also means I keep delimiter characters and sometimes
202inconsequential double quotes in the underlying byte slice (but don't worry, the
203user will never actually see them), so that copies remain as vectorized as possible.
204
205# Caveats
206
207## "Nonsensical" CSV data
208
209To remain as fast as possible, "nonsensical" CSV data is handled by this
210crate differently than it might traditionally be done.
211
212For instance, this crate's CSV parser has no concept of "beginning of field",
213which means opening quotes in the middle of a field might corrupt the output.
214(I would say this is immoral to do so in the first place but traditional parsers
215tend to deal with this case more graciously).
216
217For instance, given the following CSV data:
218
219```txt
220name,surname\njoh"n,landis\nbéatrice,babka
221```
222
223Cautious parsers would produce the following result:
224
225| name     | surname |
226| -------- | ------- |
227| joh"n    | landis  |
228| béatrice | babka   |
229
230While this crate's parser would produce the following unaligned result:
231
232| name                         | surname |
233| ---------------------------- | ------- |
234| joh"n,landis\nbéatrice,babka | \<eof\> |
235
236Keep also in mind that fields opening and closing quotes multiple
237times might lose some characters here & there (especially whitespace) because
238the parser's state machine is not geared towards this at all.
239
240Rest assured that morally valid & sensical CSV data will still be parsed
241correctly ;)
242
243## Regarding line terminators
244
245To avoid needless branching and SIMD overhead, this crate's CSV parser
246expect line terminators to be either CRLF or single LF, but not single CR.
247
248Also, to avoid state machine overhead related to CRLF at buffer boundaries
249when streaming and to make sure we skip empty lines of the file (we
250don't parse them as empty records),
251one edge case has been deemed an acceptable loss: leading CR characters
252will be trimmed from the beginning of records.
253
254For instance, given the following CSV data:
255
256```txt
257name,surname\n\rjohn,landis\r\nbéatrice,babka
258```
259
260A morally correct parser recognizing CRLF or LF line terminators should return:
261
262| name     | surname |
263| -------- | ------- |
264| \rjohn   | landis  |
265| béatrice | babka   |
266
267While the hereby crate returns:
268
269| name     | surname |
270| -------- | ------- |
271| john     | landis  |
272| béatrice | babka   |
273
274*/
275#[allow(unused_macros)]
276macro_rules! brec {
277    () => {{
278        $crate::records::ByteRecord::new()
279    }};
280
281    ($($x: expr),*) => {{
282        let mut r = $crate::records::ByteRecord::new();
283
284        $(
285            r.push_field($x.as_bytes());
286        )*
287
288        r
289    }};
290}
291
292mod buffer;
293mod core;
294mod debug;
295mod error;
296mod ext;
297mod line_reader;
298mod reader;
299mod records;
300mod searcher;
301mod seeker;
302mod splitter;
303mod total_reader;
304mod utils;
305mod writer;
306mod zero_copy_reader;
307
308pub use error::{Error, ErrorKind, Result};
309pub use line_reader::LineReader;
310pub use reader::{Reader, ReaderBuilder, ReverseReader};
311pub use records::{ByteRecord, ZeroCopyByteRecord};
312pub use searcher::searcher_simd_instructions;
313pub use seeker::{Seeker, SeekerBuilder};
314pub use splitter::{Splitter, SplitterBuilder};
315pub use total_reader::{TotalReader, TotalReaderBuilder};
316pub use utils::unescape;
317pub use writer::{Writer, WriterBuilder};
318pub use zero_copy_reader::{ZeroCopyReader, ZeroCopyReaderBuilder};