A byte-level CSV reader for Rust with borrowed fields, bounded on hostile input, plus the text
handling around it: encoding detection (decode_text), delimiter sniffing (sniff_delimiter) and
field quoting (write_field), and optional gzip / Zstandard input. No unsafe, no C, no
dependencies in the default build (the gzip and zstd features add one house crate each); builds
for wasm32-unknown-unknown with any feature set. Spun out of GridCraft's CSV
module. Version 0.1.0. MIT OR Apache-2.0.
use rusty_csv::{Dialect, Reader, StrReader};
// Bytes in, borrowed &[u8] fields out.
let mut rdr = Reader::new(b"id,note\r\n1,\"says \"\"hi\"\"\"\n", Dialect::default());
while let Some(rec) = rdr.read_record().unwrap() {
for field in rec.iter() { /* &[u8] */ }
}
// Text in, borrowed &str fields out (no per-field UTF-8 check), or owned records.
let mut rdr = StrReader::new("a,b\n1,2\n", Dialect::default());
while let Some(rec) = rdr.read_owned().unwrap() {
println!("{:?}", rec.to_vec());
}| item | what it is |
|---|---|
Reader<'a> |
reads &'a [u8]; read_record() -> Result<Option<Record<'_>>, Error> |
Record<'r> |
len, get(i) -> Option<&[u8]>, iter, to_vec, dropped() (fields past the limit) |
StrReader<'a> |
the same over &'a str; read_record() -> StrRecord<'_> with &str fields, read_owned() -> OwnedRecord |
OwnedRecord |
one String plus field offsets (inline for up to 16 fields): len, get, iter, to_vec |
read_all(text, dialect, limits) -> Vec<Vec<String>> |
the convenience path |
Dialect |
delimiter, quote (ASCII, distinct, not CR/LF), doublequote, escape: Option<u8>, blank_lines |
BlankLines |
OneEmptyField (default, GridCraft), NoFields (Python csv), Skip (csv crate), SkipWhitespace (pandas skip_blank_lines=True) |
Limits |
max_input_bytes, max_records, max_fields, excess_fields: Drop/Error, max_field_bytes; Limits::default(), Limits::unlimited() |
Error { kind, record, byte } |
ErrorKind (non-exhaustive): BadDialect, InputTooLarge, TooManyRecords, TooManyFields, FieldTooLarge, Decompress, UnsupportedCompression |
decode_text(&[u8]) -> String |
UTF-8 (BOM stripped), UTF-16 LE/BE by BOM; otherwise Windows-1256 when the bytes read as Arabic, else Windows-1252 |
decode_text_cow(&[u8]) -> Cow<str> |
the same output, borrowed when the input is already UTF-8 (no copy) |
Compression, decompress, decompress_auto |
gzip / Zstandard input by magic bytes or extension, bounded by a byte limit (features gzip, zstd) |
sniff_delimiter(&str, quote: char) -> u8 |
comma, semicolon or tab: the most consistent count per line over the first 20 non-blank lines |
needs_quotes, written_len, write_field, Writer |
GridCraft's output quoting: quote a field holding the delimiter, ", CR or LF; double inner quotes; records end CRLF |
RFC 4180 with the usual leniency, exactly GridCraft's: CR, LF and CRLF each end a record; a quote
opens a quoted field only at the start of a field and is ordinary text anywhere else (a"b is
a"b); inside quotes a doubled quote is one quote; text after a closing quote is kept ("ab"cd is
abcd); an unterminated quote runs to the end of the input; a blank line is one empty field
(configurable). There is no header handling, trimming or type inference: those belong to the
caller (GridCraft keeps its Excel-style value and date inference).
Every limit is checked while reading; memory stays at the input plus one record.
| limit | default | when exceeded |
|---|---|---|
max_input_bytes |
4 GiB | InputTooLarge before reading |
max_records |
2^32 | TooManyRecords |
max_fields |
16,384 (Excel's width) | Drop (default): the rest are read and discarded, counted in Record::dropped(); or Error |
max_field_bytes |
1 GiB | FieldTooLarge |
Hostile inputs in the tests (tests/behaviour.rs, all in one test, 0.3 s optimised): a 100 MB
unterminated quote (one borrowed field, no copy), 10 million delimiters on one line (16,384
fields kept), 2 million escaped fields on one line (dropped fields give their buffer back), 20
million line breaks, and 5 million quote/delimiter storms. Each byte is classified once; nothing is
quadratic.
The reader classifies the input 64 bytes at a time into a bitmask of the five bytes it stops at
(delimiter, quote, CR, LF, escape), then walks the set bits. The classifier is plain safe Rust in
a shape LLVM vectorises (SSE2 compares on x86-64; the obvious mask |= bit << i loop is
vectorised as 64-bit lane shifts and was rejected after reading the assembly). Unquoted fields and
quoted fields without escapes borrow from the input; only fields that need unescaping are copied,
into one buffer reused across records. Owned records copy the record's input span once and keep
offsets, inline for records of up to 16 fields, so an owned record costs one allocation (the csv
crate's StringRecord costs three; counted below).
rusty_csv = { version = "0.1", features = ["gzip", "zstd"] }use rusty_csv::{Compression, Dialect, Limits, Reader, decompress};
let limits = Limits::default();
let kind = Compression::from_extension(path).unwrap_or(Compression::detect(&bytes));
let data = decompress(&bytes, kind, limits.max_input_bytes)?; // Cow: plain input is borrowed
let mut rdr = Reader::with_limits(&data, Dialect::default(), limits);gzipuses rusty_zlib 0.1.4 directly (no flate2), with only itsrust-allocatorfeature, so it staysno_std-clean. Concatenated gzip members decode as one stream, as gzip(1) and Python do.zstduses rusty_zstd 0.5.1 with onlyalloc. Concatenated frames decode as one stream.- Format: magic bytes (
1F 8B,28 B5 2F FD) or the extension (.gz,.gzip,.zst,.zstd, as pandas'compression='infer'). A compressed input in a build without the feature is refused withUnsupportedCompression, never parsed as text. - The reader works on a slice, so compressed input is decoded first, 64 KiB at a time, into one
buffer the reader then borrows from; it is not parsed incrementally. After every chunk the decoded
size is checked against the limit (pass
Limits::max_input_bytes), so a decompression bomb stops within 64 KiB of the limit: the tests decode 512 MiB of zeros (about 0.5 MB compressed) against a 4 MiB limit and stop at 4 MiB + at most one chunk. A size the stream's own header states (gzip ISIZE, zstd content size) is used to reserve the buffer, but never more than 64 MiB up front, so a lying header cannot allocate either. cargo check --target wasm32-unknown-unknownpasses with no features,gzip,zstd, and both.
rusty_csv against the csv crate 1.4.0 (BurntSushi; arrow-csv is
built on it), on a generated corpus (bench/gen_corpus.py, seeded, no blank lines or ragged rows,
so both readers do the same work with default settings):
| file | size | records | fields per record | content |
|---|---|---|---|---|
| narrow | 134 MB | 2,919,129 | 6 | id, word, decimal, date, category, boolean |
| wide | 134 MB | 77,360 | 400 | wide table |
| quotes | 134 MB | 578,195 | 6 | quoted text with embedded quotes, delimiters and newlines |
| numeric | 268 MB | 2,238,372 | 12 | numbers |
| utf8 | 134 MB | 1,143,779 | 7 | CJK, Cyrillic, Arabic, accents, emoji |
Throughput in MB/s, the fastest round of 10. Higher is better. "Speedup" is the median over the 10 paired rounds of csv's time divided by rusty_csv's.
| file | rusty_csv borrowed (Reader) |
csv ByteRecord |
speedup | rusty_csv owned (OwnedRecord) |
csv StringRecord |
speedup |
|---|---|---|---|---|---|---|
| narrow | 832 | 506 | 1.66× | 309 | 240 | 1.31× |
| wide | 615 | 368 | 1.67× | 464 | 341 | 1.34× |
| quotes | 988 | 753 | 1.33× | 544 | 506 | 1.08× |
| numeric | 1200 | 683 | 1.75× | 602 | 414 | 1.46× |
| utf8 | 1552 | 760 | 2.05× | 329 | 268 | 1.25× |
rusty_csv was faster in 10 of 10 rounds on every file and both paths. The control pair (rusty_csv
against itself) gave speedups between 0.99× and 1.02×, so differences under about 2% are noise.
Both readers run with no header handling and ragged rows allowed (csv: has_headers(false), flexible(true)). The borrowed arms read every field without keeping the record (csv's read_byte_record into one reused ByteRecord). The owned arms produce a record the caller can keep: csv's records() iterator, which makes a new StringRecord for each, and StrReader::read_owned. Both validate UTF-8 inside the timed region. A csv caller who reuses one StringRecord with read_record avoids the per-record allocations but cannot keep the record; that path is not measured here.
Heap allocations (rusty_alloc's own counters, examples/alloc_census.rs):
| path | rusty_csv | csv |
|---|---|---|
| borrowed | 3 to 9 per file (buffers only) | 16 to 27 per file |
| owned, up to 16 fields | 1 per record | 3 per record |
| owned, more than 16 fields | 2 per record | 3 per record |
Allocator. The same benchmark built with rusty_alloc
2.7.0 as the program's global allocator (examples/bench_rusty_alloc.rs; the library never sets
one). Time with rusty_alloc as a fraction of time with the Windows system allocator (median of 10
paired rounds; below 1 means rusty_alloc is faster):
| file | rusty_csv owned | csv owned | rusty_csv borrowed |
|---|---|---|---|
| narrow | 0.82 | 0.65 | 1.04 |
| wide | 1.00 | 1.01 | 0.98 |
| quotes | 0.91 | 0.82 (noisy: 0.46 to 1.05) | 0.98 |
| numeric | 0.82 | 0.75 | 1.04 |
| utf8 | 0.93 | 0.84 | 1.00 |
The allocator matters where records allocate (owned paths on narrow rows) and not where they don't (borrowed fields, or wide rows where allocation is a small share of the work).
Method (bench/run.ps1, bench/summarize.py). Intel Core i7-14650HX, 32 GB, Windows 11, rustc
1.100.0, --release. One process per run, pinned to one core (not core 0) at High priority; the file
is read into memory first, and 12 parse loops are timed with the monotonic clock. The two arms of a
pair alternate ABBA across 10 rounds. Each line records the work done (records, fields, field
bytes), and the summary refuses a pair whose counts differ. A run's figure is its fastest loop, so a
run that was descheduled for part of its time (a few were) still reports its undisturbed speed.
Raw logs: bench/results/. Reproduce:
python -I bench/gen_corpus.py <dir>
cargo build --release --example bench --example bench_rusty_alloc
powershell -File bench/run.ps1 -Exe target/release/examples/bench.exe -Corpus <dir> -Out readers.txt
python -I bench/summarize.py readers.txt
Record splitting is checked against three references on 20,310 generated inputs (oracle/compare.py,
seed 20261205). The inputs are built from awkward pieces: a quote in the middle of a field,
doubled quotes, embedded newlines, lone CR, LF and CRLF endings mixed in one file, blank lines,
trailing delimiters, a BOM, ragged rows, fields of several KB, empty input, and unterminated quotes.
They run under comma and semicolon delimiters, " and ' quotes, doublequote on and off, and
with and without a \ escape. Only the split is compared (fields as strings), never typing.
| reference | cases | result |
|---|---|---|
GridCraft's previous parser (tests/common/legacy.rs) |
14,560 (its dialects) | identical in every case |
Python 3.11 csv module |
20,310 | identical, given the two differences below |
pandas 3.1.2 read_csv (C engine), skip_blank_lines=False |
20,310 | identical, given the differences below |
pandas 3.1.2 read_csv (C engine), skip_blank_lines=True |
20,310 | identical, given the differences below |
pandas is compared with header=None, dtype=str, keep_default_na=False. pandas pads short rows to
the widest row, so for ragged inputs the comparison strips trailing empty fields on both sides.
Differences, all intentional:
| with | cases | input | pandas or Python | rusty_csv | why |
|---|---|---|---|---|---|
Python csv |
13,937 | a blank line | [] (no fields) |
[""] (one empty field) |
GridCraft's rule. BlankLines::NoFields gives Python's result. |
Python csv |
117 | an escape character as the last byte, a\ |
["a\n"] |
["a\\"] |
Python invents a newline; pandas raises (next row). rusty_csv keeps the byte as written. |
| pandas | 1,917 | an unterminated quote, "abc |
raises ParserError: EOF inside string |
["abc"] |
GridCraft reads the rest of the input as the field; a reader that must not fail on damaged files needs that. |
| pandas | 115 | an escape character as the last byte, a\ |
raises ParserError: EOF following escape character |
["a\\"] |
as with an unterminated quote, a damaged ending is kept rather than refused. |
pandas, skip_blank_lines=True only |
257 | CR followed by a delimiter, a\r,b |
splits differently | the same split as with skip_blank_lines=False |
a pandas tokenizer quirk (its EAT_CRNL_NOP state) that appears only in skip mode. BlankLines::SkipWhitespace gives pandas' blank-line skipping without it. |
To reproduce pandas' splitting, use Dialect { blank_lines: BlankLines::SkipWhitespace, .. } for
skip_blank_lines=True (the default), and BlankLines::OneEmptyField with trailing empties
stripped for False. Set delimiter, quote, doublequote and escape to the same values passed
to read_csv.
The unit tests (tests/behaviour.rs, tests/vs_legacy.rs, tests/compressed.rs) cover the same
rules and the hostile inputs listed under Limits. Reproduce the comparison with
python -I oracle/compare.py (needs pandas).
MIT OR Apache-2.0, at your option. Derived from GridCraft (Copyright (c) 2026 ArtCraft Team and the GridCraft contributors, same licenses); see NOTICE.