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.

convto zero-dependency structured data and binary header probe pipeline Nine structured data formats parse into a shared ordered Value IR with 128-level depth guards and 64 KiB streaming emission to power seven subcommands, while a two-stage 4 KiB stack header probe inspects binary containers, media, databases, and executables without subprocesses. 9 Structured Formats JSON/L, YAML, TOML, INI, ENV, XML, CSV/TSV Containers & DBs TAR, ZIP64, GZIP, MP4, SQLite 3, Fonts Media & Executables Images, Audio, PDF, ELF, Mach-O, PE32+ Unified Value IR (src/data.rs) Object(Vec<(String, Value)>) MAX_NESTING_DEPTH = 128 OutBuf::streaming (64 KiB) Header Probe (src/info.rs) 4 KiB stack -> 256 KiB Single fs::metadata() + seek Zero external subprocesses 7 Data Subcommands to, query, diff, merge validate, fmt, stats Atomic temp + sync + rename convto info Dimensions, EXIF, codecs, pages TAR/ZIP/SQLite/ELF/Mach-O/PE Text or NDJSON (--json)
Two zero-dependency subsystems inside one 1.2 MB binary: a single 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:

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):

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