Nine formats, binary header probes, and a 62x serializer rewrite in safe Rust
Shell scripts and CI pipelines spend an unreasonable amount of glue converting config files and inspecting artifacts. A single repository often installs jq for JSON, yq for YAML, a Python one-liner for TOML, INI, CSV, or XML, file for executables, sqlite3 for database headers, and ffprobe just to read image dimensions. Each tool carries its own flag dialect, exit codes, and version drift across developer laptops and minimal Linux containers.
convto started as a Linux file-manager context menu wrapper around media converters, then grew an internal pure-Rust structured-data and header-probing engine. Compiled with opt-level = "s", LTO, strip = true, and zero [dependencies] in Cargo.toml (MSRV 1.80, #![forbid(unsafe_code)]), the entire binary weighs 1,196,656 bytes (1.2 MB) and handles all structured formats and binary header inspection without spawning a subprocess. You can test the structured-data converter, path query, and semantic diff engine directly in the browser playground.
Value IR serving 9 formats across 7 commands, and a two-stage header prober serving convto info.
1. One ordered IR across nine structured formats and seven commands
Every structured-data parser in src/data.rs produces the same seven-variant enum: Null, Bool(bool), Int(i64), Float(f64), Str(String), Array(Vec<Value>), and Object(Vec<(String, Value)>). Storing objects as a key-value vector rather than a hash map keeps original field ordering deterministic across round-trips, while --sort-keys applies recursive alphabetical ordering only when requested.
Sharing one representation across JSON, JSONL/NDJSON, YAML, TOML, INI, ENV, XML, CSV, and TSV means adding a format immediately unlocks all seven subcommands: cross-format conversion (to), dotted/bracket/wildcard path evaluation (query), semantic order-insensitive comparison (diff), left-to-right recursive overlay merging (merge, with --array-strategy replace|append|unique), syntax verification (validate), canonical formatting (fmt), and schema/numeric summaries (stats).
Real format semantics still require careful boundaries at the IR edges:
ENVparsesKEY=VALUEandexport KEY=VALUE, preserves unquoted#hexvalues while stripping inline comments, and flattens nested objects with_on output while rejecting non-object roots and flattened key collisions.XMLmaps element attributes to@attrkeys, preserves mixed and attributed content under#text, promotes repeated sibling tags to arrays, decodes XML 1.0 predefined entities plus decimal and hexadecimal character references, and enforces exact closing-tag matching.convto statsinfers column types across heterogeneous documents (including automatic numeric, boolean, and null detection inside string-typed CSV and TSV cells), bounds distinct-value tracking atMAX_UNIQUE_TRACKED = 100_000so high-cardinality columns cannot exhaust memory, and computesmin,max, Kahan-summedmean, andmedian.
2. Parser hardening, a fuzz-caught XML bug, and atomic formatting
Hand-written parsers only hold up if adversarial inputs are treated as first-class test cases. Every recursive parser in src/data.rs enforces const MAX_NESTING_DEPTH: usize = 128 across JSON arrays and objects, YAML block and flow structures, TOML inline and dotted tables, INI dotted sections, and XML element trees. In tests/parser_fuzz.rs, deterministic Xorshift64 harnesses feed 1,500 adversarial syntax-soup strings, 1,000 arbitrary UTF-8 strings, and 129-to-512-level nesting bombs through every parser and through parse_query_path, asserting clean errors with zero panics.
XML adds a classic parser hazard: internal <!DOCTYPE> subsets can define recursive entity expansions (Billion Laughs) or external entities (XXE). In src/data.rs, skip_doctype() skips the declaration structurally without ever registering or expanding DTD entities. Deterministic fuzzing caught a real crash inside that skipper on its first run. Walking bytes one index at a time (self.pos += 1) allowed self.pos to land inside a multi-byte UTF-8 sequence before checking self.rest().starts_with("<!--"), which sliced &str on a non-character boundary and panicked. Checking the raw byte slice fixed it permanently:
} else if self.bytes[self.pos..].starts_with(b"<!--") {
self.skip_comment()?;
} else if b == b'[' && !in_subset {
in_subset = true;
self.pos += 1;
} else if b == b']' && in_subset {
in_subset = false;
self.pos += 1;
}
On the write path, both convto merge -o and convto fmt use write_file_atomic() in src/merge.rs. It opens a unique sibling temporary file (.convto-merge-<pid>-<seq>.tmp) guarded by a drop struct that unlinks on early error, writes the full payload, calls file.sync_all(), and commits with fs::rename(). Inside format_file() in src/fmt_cmd.rs, comparing formatted.as_bytes() != original.as_bytes() skips touching disk whenever a file is already canonical, preserving mtime for incremental builds while letting convto fmt --check fail CI with exit code 1 and --diff print bounded LCS unified diffs (capped at 250,000 DP cells).
3. Pure-Rust binary header probes with zero subprocesses
Inspecting hundreds of mixed files by spawning file or ffprobe per path spends most of its wall time in fork and exec. In src/info.rs, inspect_file() executes a single fs::metadata() call and reads the opening bytes into a 4 KiB stack array (INITIAL_HEADER_PROBE_BYTES = 4096), escalating up to 256 KiB only for formats that need a deeper scan (such as JPEG segments or PDF page markers) or seeking directly to container trailers.
Every probe validates bounds with checked arithmetic before indexing and runs under 4,000 deterministic fuzz inputs in tests/parser_fuzz.rs (2,000 random buffers plus 2,000 mutated real binary headers across 34 seeds):
- Images, audio, and PDF: PNG, JPEG SOF0/1/2 plus
APP1EXIF orientation, GIF, WebP (VP8, VP8L, VP8X), BMP, little/big-endian TIFF IFD0, ICO (mapping0 => 256), QOI, PSD, Netpbm (P1..P6), SVG, AVIF/HEICispeboxes, WAV, FLACSTREAMINFO, Ogg Opus/Vorbis, MP3 (skipping synchsafe ID3v2 tags), and PDF version/page counts. - Archives and containers: tail-seeking ZIP/ZIP64 EOCD and Central Directory (covering JAR, WHL, and EPUB), RFC 1952 GZIP headers and trailer
ISIZE, box-seeking ISO BMFF MP4/MOV/M4A (moov->mvhdandtrak->tkhd), SFNT/WOFF/WOFF2 fonts, and streamingseek-basedustar/GNU TAR (handling GNU base-256 sizes and 512-byte header checksum sniffing for misnamed files). - SQLite 3 and native executables:
probe_sqlite_info()decodes the 100-byte SQLite header (mapping raw page size1 -> 65536, detecting WAL vs rollback mode, text encoding, schema cookie, user version, and application ID).probe_binary_exec_info()identifies ELF32/ELF64, Mach-O 32/64-bit, Mach-O Universal Fat (disambiguating0xCAFEBABEfrom Java.classfiles by bounding1 <= nfat <= 32and validating every slicecputype), and PE32/PE32+/PE ROM including DOS stubs past 4 KiB.
4. The oa-verified 62x serializer and probe rewrite
Early versions of src/data.rs worked on small configs and fell apart on megabyte payloads. Profiling with oa in convto#21 pinned down three bottlenecks: JsonParser::parse_string() re-validated UTF-8 over remaining string slices in O(N^2) time, large JSON and YAML objects deduplicated keys via O(K^2) linear scans on every insertion, and inspect_file() issued three stat() calls plus a 256 KiB read per image.
Fixing them took targeted data-structure changes rather than unsafe tricks: bulk-slicing contiguous unescaped chunks from borrowed &str in parse_string(), switching ObjectBuilder to a lazy HashMap index once an object reaches 16 keys, dropping the input String right after parsing inside convert_data_to_writer_with_options(), flushing serialized output through a 64 KiB OutBuf::streaming buffer, and adding zero-AST streaming paths for csv/tsv -> json/jsonl. That streaming change came directly from oa's Pareto gate rejecting an earlier String::with_capacity(input.len()) draft over a +7.3% Peak RSS bump.
Workload (--pin-core 0) |
Before -> After | Speedup (95% CI, p) | Peak RSS |
|---|---|---|---|
json -> toml (592 KB) |
1164.12 -> 18.25 ms | 62.14x [54.30x, 69.79x], 0.0001 |
Pareto clean |
json -> yaml (592 KB) |
1072.40 -> 17.97 ms | 60.08x [52.96x, 65.68x], 0.0001 |
Pareto clean |
json -> csv (385 KB, 3k rows) |
820.28 -> 17.73 ms | 46.22x [42.51x, 49.17x], 0.0001 |
Pareto clean |
Large-object json -> yaml (5k keys) |
451.89 -> 17.26 ms | 24.92x [24.68x, 26.51x], 0.0001 |
Pareto clean |
csv -> json (4.5 MB, 50k rows) |
62.98 -> 28.87 ms | 2.17x, 0.0001 |
66,104 -> 23,000 KiB (-65.2%) |
info -r --json (1,000 images, 300 MB) |
71.51 -> 19.36 ms | 3.69x [3.58x, 3.85x], 0.0001 |
Pareto clean |
Every run above used oa compare --check-output --pairs 11 --warmup 2 --metric pareto --pin-core 0 with bit-for-bit identical output SHA-256 across all 7 benchmark workloads. The repository currently carries 152 Rust tests (120 unit tests plus 32 integration and fuzz tests) alongside the headless Python GUI suite.
Limitations
- Structured data conversion is zero-dependency, while raster/video/audio transcoding and document conversion still delegate to installed system tools (ImageMagick,
ffmpeg, LibreOffice,pandoc), checked up front byconvto doctor. - XML parsing targets data-oriented XML 1.0 documents and skips
<!DOCTYPE>declarations by design; documents that rely on DTD-defined custom entities or XML namespaces with prefix remapping are out of scope. - TOML and CSV/TSV cannot represent arbitrary heterogeneous JSON values without loss (for example, top-level arrays or
nullin TOML, or nested objects in flat tables);convtorejects incompatible shapes with explicit errors instead of silently dropping fields. convto statscaps distinct-value tracking at 100,000 unique entries per key to bound memory on multi-million-row datasets, reporting overflow explicitly rather than spilling to disk.