jsontape 0.1.4

A minimalistic allocator-aware, zero-copy JSON & JSON5 parser in pure Rust
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Criterion suite comparing JsonTape's parsers against `serde_json`, `simd-json`, and the `json5` crate.
//!
//! # Apples-to-apples notes
//!
//! Every configuration below fully parses and validates its input in one call — UTF-8 checked, escapes checked,
//! structure checked — and produces a fully navigable document; none of them are lazy or defer syntax errors. All of
//! them also deduplicate repeated object keys with last-wins semantics. What differs is the shape of what comes out,
//! which every id spells out as `backend-shape`:
//!
//! - `jsontape-owned` — mutable `Json`; strings decoded into the document's allocator at parse.
//! - `jsontape-view` — immutable zero-copy `JsonView`; strings validated, left escaped, decoded on first use.
//! - `jsontape-view-bound` — the same view, permanently paired with its source.
//! - `jsontape-owned-arena`, `jsontape-view-arena` — either parse into a reused bump arena, reset between documents.
//! - `jsontape-owned-comments` — the owned tree plus round-trippable comments, which no peer here can produce.
//! - `serde-owned` — `serde_json::from_slice`; its `BTreeMap` object replaces source key order with sorted order.
//! - `simdjson-owned` — `to_owned_value_with_buffers`; hashes keys, rewrites input in place, copies strings out.
//! - `simdjson-borrowed` — `to_borrowed_value_with_buffers`; `Cow` strings into the unescaped input buffer.
//! - `json5-owned` — the `json5` crate into a `Value`; every number becomes `f64`, so integers past 2^53 round.
//!
//! Only `jsontape` keeps source key order and exact integer lanes past 64 bits. So the `-owned` rows read against each
//! other, and `jsontape-view` against `simdjson-borrowed` — with the caveat that the view keeps strings escaped
//! (validation done, decoding deferred) while simd-json unescapes eagerly. JSON5 is a superset of JSON, so the `json5`
//! rows run in the strict group as well as the JSON5 one.
//!
//! simd-json requires a mutable input buffer, so its rows re-memcpy the pristine source into one reused buffer each
//! iteration — no per-iteration allocation, just the copy an in-place parser inherently needs when the source must be
//! kept — and reuse one set of scratch `Buffers` across runs (its analogue to JsonTape reusing an arena). Every row
//! times parsing plus the drop of that iteration's document, which is exactly where the `-arena` rows' O(1) teardown
//! shows up.

use allocator_api2::alloc::{AllocError, Allocator, Layout};
use core::cell::Cell;
use core::ops::Range;
use core::ptr::NonNull;
use criterion::measurement::WallTime;
use criterion::{black_box, criterion_group, criterion_main, BenchmarkGroup, BenchmarkId, Criterion, Throughput};
use jsontape::{parse, parse_in, parse_with, view, view_bound, view_in, view_in_bound_with, view_with, ParseOptions};

/// `jsontape::parse`: owned, mutable DOM; strings decoded into the document's allocator at parse time, keys deduped in
/// source order.
const JSONTAPE_OWNED: &str = "jsontape-owned";
/// `jsontape::view`: immutable zero-copy DOM of spans into the source; strings validated at parse but kept escaped,
/// decode deferred to first use.
const JSONTAPE_VIEW: &str = "jsontape-view";
/// `jsontape::view_bound`: the same zero-copy DOM, permanently paired with its source so navigation cannot receive
/// mismatched bytes.
const JSONTAPE_VIEW_BOUND: &str = "jsontape-view-bound";
/// `jsontape::parse_in` into a reused bump arena, reset between documents.
const JSONTAPE_OWNED_ARENA: &str = "jsontape-owned-arena";
/// `jsontape::view_in` into a reused bump arena, reset between documents.
const JSONTAPE_VIEW_ARENA: &str = "jsontape-view-arena";
/// `jsontape::parse_with` and `preserve_comments(true)`: the owned DOM plus round-trippable comments — the feature the
/// peer crates drop.
const JSONTAPE_OWNED_COMMENTS: &str = "jsontape-owned-comments";
/// `serde_json::from_slice::<Value>`: owned, mutable DOM; its object is a `BTreeMap`, so source key order is replaced
/// by sorted order.
const SERDE_OWNED: &str = "serde-owned";
/// `simd_json::to_owned_value_with_buffers`: owned, mutable DOM; hashed object, input rewritten in place from a reused
/// buffer.
const SIMDJSON_OWNED: &str = "simdjson-owned";
/// `simd_json::to_borrowed_value_with_buffers`: mutable DOM of `Cow` strings borrowing the (in-place unescaped) input
/// buffer — the closest peer to the JsonTape views.
const SIMDJSON_BORROWED: &str = "simdjson-borrowed";
/// `json5::from_str::<serde_json::Value>`: owned, mutable DOM via the PEG-based json5 crate; every number becomes an
/// `f64`.
const JSON5_OWNED: &str = "json5-owned";

const SMALL: usize = 256;
const KIB_4: usize = 4 * 1024;
const KIB_64: usize = 64 * 1024;

/// Arena slab size for the reuse benches. Sized well past any single document's DOM (and any NDJSON record's) plus the
/// geometric-growth slack the parser's vectors leave behind between resets.
const ARENA_BYTES: usize = 256 * 1024 * 1024;

/// A single-slab bump arena for the reuse benchmark: an allocation bumps a cursor, deallocation is a no-op, and `reset`
/// rewinds the cursor so one region of memory serves document after document without ever calling the global allocator.
/// This is the packed, drop-once (here reset-once) layout JsonTape is built for.
///
/// `reset` takes `&self` so it fits criterion's `Fn` closures; that makes it a footgun (resetting with a live
/// allocation aliases freed memory), sound here only because criterion drops each result before the next reset. Real
/// code should reach for an arena with a checked `&mut self` reset — see the README.
struct BumpArena {
    base: *mut u8,
    capacity: usize,
    head: Cell<usize>,
}

impl BumpArena {
    fn with_capacity(capacity: usize) -> Self {
        let layout = Layout::from_size_align(capacity, 64).unwrap();
        // Freed in `Drop`; `capacity` is non-zero for every call site here.
        let base = unsafe { std::alloc::alloc(layout) };
        assert!(!base.is_null(), "arena slab allocation failed");
        BumpArena {
            base,
            capacity,
            head: Cell::new(0),
        }
    }

    /// Rewinds the cursor so the next document reuses the same memory. Any values still borrowing the arena must be
    /// dropped first (criterion drops each iteration's result before the next call, and the streaming loops below drop
    /// each record's value before the next `reset`).
    fn reset(&self) {
        self.head.set(0);
    }
}

impl Drop for BumpArena {
    fn drop(&mut self) {
        let layout = Layout::from_size_align(self.capacity, 64).unwrap();
        unsafe { std::alloc::dealloc(self.base, layout) };
    }
}

// Implemented for the shared reference, matching the `parse_in` doctest: `&BumpArena` is `Copy`, so it satisfies the
// parser's `Allocator + Clone` bound directly.
unsafe impl Allocator for &BumpArena {
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        let start = (self.head.get() + layout.align() - 1) & !(layout.align() - 1);
        let end = start.checked_add(layout.size()).ok_or(AllocError)?;
        if end > self.capacity {
            return Err(AllocError);
        }
        self.head.set(end);
        // `start` is within the slab and aligned; the returned slice covers the request.
        let ptr = unsafe { NonNull::new_unchecked(self.base.add(start)) };
        Ok(NonNull::slice_from_raw_parts(ptr, layout.size()))
    }

    unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {}
}

struct Workload {
    name: String,
    source: Vec<u8>,
}

fn named_sizes(kind: &str, make: impl Fn(usize) -> Vec<u8>) -> Vec<Workload> {
    [SMALL, KIB_4, KIB_64]
        .into_iter()
        .map(|bytes| Workload {
            name: format!("{kind}-{bytes}b"),
            source: make(bytes),
        })
        .collect()
}

fn plain_string(bytes: usize) -> Vec<u8> {
    let mut source = Vec::with_capacity(bytes + 4);
    source.extend_from_slice(b"[\"");
    while source.len() + 2 < bytes {
        source.extend_from_slice(b"plain-string-scanner-run-");
    }
    source.extend_from_slice(b"\"]");
    source
}

fn escaped_string(bytes: usize) -> Vec<u8> {
    let mut source = Vec::with_capacity(bytes + 4);
    source.extend_from_slice(b"[\"");
    while source.len() + 2 < bytes {
        source.extend_from_slice(br#"plain\u00e9\\\"run\n"#);
    }
    source.extend_from_slice(b"\"]");
    source
}

fn numeric_array(bytes: usize) -> Vec<u8> {
    let mut source = Vec::with_capacity(bytes + 2);
    source.push(b'[');
    let mut value = 0_u64;
    while source.len() + 24 < bytes {
        if source.len() > 1 {
            source.push(b',');
        }
        source.extend_from_slice(value.to_string().as_bytes());
        value = value.wrapping_mul(1_000_003).wrapping_add(97);
    }
    source.push(b']');
    source
}

fn object_keys(bytes: usize) -> Vec<u8> {
    let mut source = Vec::with_capacity(bytes + 2);
    source.push(b'{');
    let mut key = 0_usize;
    while source.len() + 48 < bytes {
        if source.len() > 1 {
            source.push(b',');
        }
        source.extend_from_slice(format!(r#""field_{key:06}":"value-{key:06}-payload""#).as_bytes());
        key += 1;
    }
    source.push(b'}');
    source
}

fn nested_document() -> Vec<u8> {
    let mut source = Vec::new();
    for level in 0..32 {
        source.extend_from_slice(format!(r#"{{"level_{level}":"#).as_bytes());
    }
    source.extend_from_slice(br#"[0,1,2,{"leaf":true}]"#);
    // `repeat().take()` rather than `repeat_n`, which needs Rust 1.82 and would push the crate's declared MSRV up for a
    // dev-only benchmark.
    source.extend(core::iter::repeat(b'}').take(32));
    source
}

fn json5_comments(bytes: usize) -> Vec<u8> {
    let mut source = Vec::with_capacity(bytes + 8);
    source.extend_from_slice(b"{\n");
    let mut key = 0_usize;
    while source.len() + 56 < bytes {
        source.extend_from_slice(
            format!("  // key {key}\n  field_{key}: 'escaped \\u00e9 value', /* tail */\n").as_bytes(),
        );
        key += 1;
    }
    source.extend_from_slice(b"}\n");
    source
}

fn strict_workloads() -> Vec<Workload> {
    let mut workloads = Vec::new();
    workloads.extend(named_sizes("plain-string", plain_string));
    workloads.extend(named_sizes("escaped-string", escaped_string));
    workloads.extend(named_sizes("numeric-array", numeric_array));
    workloads.extend(named_sizes("object-keys", object_keys));
    workloads.push(Workload {
        name: "nested-32".to_owned(),
        source: nested_document(),
    });
    workloads
}

fn json5_workloads() -> Vec<Workload> {
    named_sizes("comments-trailing", json5_comments)
}

/// JsonTape's global-allocator parses: decoded owned DOM, zero-copy view, and source-bound view. Shared by every
/// whole-document parse group.
fn bench_jsontape_global(group: &mut BenchmarkGroup<'_, WallTime>, name: &str, source: &[u8]) {
    group.bench_function(BenchmarkId::new(JSONTAPE_OWNED, name), |bench| {
        bench.iter(|| black_box(parse(black_box(source)).unwrap()))
    });
    group.bench_function(BenchmarkId::new(JSONTAPE_VIEW, name), |bench| {
        bench.iter(|| black_box(view(black_box(source)).unwrap()))
    });
    group.bench_function(BenchmarkId::new(JSONTAPE_VIEW_BOUND, name), |bench| {
        bench.iter(|| black_box(view_bound(black_box(source)).unwrap()))
    });
}

/// The `serde_json` and `simd-json` peers. `serde_json` and the owned simd-json row eagerly decode every number and
/// string into owned storage, so they are same-output-shape comparisons to `jsontape-owned`; the borrowed simd-json row
/// keeps `Cow` spans into the input and reads against the views. simd-json rewrites its input in place, so both its
/// rows re-memcpy the pristine source into one reused buffer per iteration and share one set of scratch `Buffers`
/// across runs.
fn bench_dom_peers(group: &mut BenchmarkGroup<'_, WallTime>, name: &str, source: &[u8]) {
    group.bench_function(BenchmarkId::new(SERDE_OWNED, name), |bench| {
        bench.iter(|| black_box(serde_json::from_slice::<serde_json::Value>(black_box(source)).unwrap()))
    });
    group.bench_function(BenchmarkId::new(SIMDJSON_OWNED, name), |bench| {
        let mut buffers = simd_json::Buffers::new(source.len());
        let mut buffer = source.to_vec();
        bench.iter(|| {
            buffer.copy_from_slice(black_box(source));
            black_box(simd_json::to_owned_value_with_buffers(buffer.as_mut_slice(), &mut buffers).unwrap())
        })
    });
    group.bench_function(BenchmarkId::new(SIMDJSON_BORROWED, name), |bench| {
        let mut buffers = simd_json::Buffers::new(source.len());
        let mut buffer = source.to_vec();
        bench.iter(|| {
            buffer.copy_from_slice(black_box(source));
            black_box(simd_json::to_borrowed_value_with_buffers(buffer.as_mut_slice(), &mut buffers).unwrap());
        })
    });
}

/// The `json5` crate parsing from a `&str` into `serde_json::Value`. JSON5 is a superset of JSON, so this peer joins
/// both the strict and the json5 groups.
///
/// Its API takes a `&str`, so the UTF-8 validation the other rows perform on their `&[u8]` inputs happens here in
/// `from_utf8` — timed, to keep the validation work identical across rows.
fn bench_json5_crate(group: &mut BenchmarkGroup<'_, WallTime>, name: &str, source: &[u8]) {
    group.bench_function(BenchmarkId::new(JSON5_OWNED, name), |bench| {
        bench.iter(|| {
            let text = core::str::from_utf8(black_box(source)).unwrap();
            black_box(json5::from_str::<serde_json::Value>(text).unwrap())
        })
    });
}

fn bench_strict_parse(c: &mut Criterion) {
    let workloads = strict_workloads();
    let mut group = c.benchmark_group("parse-strict");
    for workload in &workloads {
        group.throughput(Throughput::Bytes(workload.source.len() as u64));
        bench_jsontape_global(&mut group, &workload.name, &workload.source);
        bench_dom_peers(&mut group, &workload.name, &workload.source);
        bench_json5_crate(&mut group, &workload.name, &workload.source);
    }
    group.finish();
}

fn bench_json5_parse(c: &mut Criterion) {
    let options = ParseOptions::json5();
    let comment_options = ParseOptions::json5().preserve_comments(true);
    let workloads = json5_workloads();
    let mut group = c.benchmark_group("parse-json5");
    for workload in &workloads {
        group.throughput(Throughput::Bytes(workload.source.len() as u64));
        group.bench_with_input(
            BenchmarkId::new(JSONTAPE_OWNED, &workload.name),
            &workload.source,
            |bench, source| bench.iter(|| black_box(parse_with(black_box(source), &options).unwrap())),
        );
        // The comment-preserving round trip — the one output shape no peer here can produce — priced against the
        // comment-dropping rows above.
        group.bench_with_input(
            BenchmarkId::new(JSONTAPE_OWNED_COMMENTS, &workload.name),
            &workload.source,
            |bench, source| bench.iter(|| black_box(parse_with(black_box(source), &comment_options).unwrap())),
        );
        group.bench_with_input(
            BenchmarkId::new(JSONTAPE_VIEW, &workload.name),
            &workload.source,
            |bench, source| bench.iter(|| black_box(view_with(black_box(source), &options).unwrap())),
        );
        group.bench_with_input(
            BenchmarkId::new(JSONTAPE_VIEW_BOUND, &workload.name),
            &workload.source,
            |bench, source| {
                bench.iter(|| {
                    black_box(view_in_bound_with(black_box(source), allocator_api2::alloc::Global, &options).unwrap())
                })
            },
        );
        // The json5 crate is the natural JSON5 peer; serde_json and simd-json cannot parse these documents at all.
        bench_json5_crate(&mut group, &workload.name, &workload.source);
    }
    group.finish();
}

/// Compact serialization from an already-parsed document to a fresh `String`. Every row renders the same document, so
/// these are directly comparable; the JsonTape view rows re-emit their still-escaped source spans verbatim where the
/// owned rows re-escape decoded strings.
fn bench_serialize(c: &mut Criterion) {
    let cases = [
        ("object-4k", object_keys(KIB_4)),
        ("numeric-array-4k", numeric_array(KIB_4)),
        ("nested-32", nested_document()),
    ];
    let mut group = c.benchmark_group("serialize");
    for (name, source) in &cases {
        let owned = parse(source).unwrap();
        let borrowed = view(source).unwrap();
        let bound = view_bound(source).unwrap();
        let serde_value: serde_json::Value = serde_json::from_slice(source).unwrap();
        let simd_value = {
            let mut buffer = source.to_vec();
            simd_json::to_owned_value(&mut buffer).unwrap()
        };
        group.throughput(Throughput::Bytes(source.len() as u64));
        group.bench_with_input(BenchmarkId::new(JSONTAPE_OWNED, name), &owned, |bench, document| {
            bench.iter(|| black_box(document.to_string()))
        });
        group.bench_with_input(BenchmarkId::new(JSONTAPE_VIEW, name), &borrowed, |bench, document| {
            bench.iter(|| black_box(document.to_json_string(black_box(source))))
        });
        group.bench_with_input(
            BenchmarkId::new(JSONTAPE_VIEW_BOUND, name),
            &bound,
            |bench, document| bench.iter(|| black_box(document.to_json_string())),
        );
        group.bench_with_input(BenchmarkId::new(SERDE_OWNED, name), &serde_value, |bench, document| {
            bench.iter(|| black_box(serde_json::to_string(document).unwrap()))
        });
        group.bench_with_input(
            BenchmarkId::new(SIMDJSON_OWNED, name),
            &simd_value,
            |bench, document| bench.iter(|| black_box(simd_json::to_string(document).unwrap())),
        );
    }
    group.finish();
}

/// Reads the dataset directory named by the `JSONTAPE_DATA` environment variable, keeping only files whose extension is
/// in `extensions`. Empty when the variable is unset, so the synthetic benches run standalone. See the README for the
/// download commands.
fn read_data_dir(extensions: &[&str]) -> Vec<(String, Vec<u8>)> {
    let Ok(dir) = std::env::var("JSONTAPE_DATA") else {
        return Vec::new();
    };
    let mut files = Vec::new();
    let entries =
        std::fs::read_dir(&dir).unwrap_or_else(|error| panic!("JSONTAPE_DATA dir {dir:?} unreadable: {error}"));
    for entry in entries.flatten() {
        let path = entry.path();
        let extension = path.extension().and_then(|extension| extension.to_str());
        if !extension.is_some_and(|extension| extensions.contains(&extension)) {
            continue;
        }
        let source = std::fs::read(&path).unwrap_or_else(|error| panic!("reading {path:?}: {error}"));
        let name = path.file_stem().unwrap().to_string_lossy().into_owned();
        files.push((name, source));
    }
    files.sort_by(|left, right| left.0.cmp(&right.0));
    files
}

/// Single-document datasets: each `*.json` file becomes one whole-document workload.
fn load_docs() -> Vec<Workload> {
    read_data_dir(&["json"])
        .into_iter()
        .map(|(name, source)| Workload { name, source })
        .collect()
}

struct StreamWorkload {
    name: String,
    source: Vec<u8>,
    records: Vec<Range<usize>>,
}

/// Byte ranges of each non-blank line in `source`, with any trailing `\r` and the `\n` excluded. A final line without a
/// newline is included.
fn split_records(source: &[u8]) -> Vec<Range<usize>> {
    let mut records = Vec::new();
    let mut start = 0;
    for index in 0..=source.len() {
        if index != source.len() && source[index] != b'\n' {
            continue;
        }
        let mut end = index;
        if end > start && source[end - 1] == b'\r' {
            end -= 1;
        }
        if source[start..end].iter().any(|byte| !byte.is_ascii_whitespace()) {
            records.push(start..end);
        }
        start = index + 1;
    }
    records
}

/// NDJSON / JSON Lines datasets: each `*.ndjson`/`*.jsonl` file becomes one streaming workload whose records are parsed
/// one per line.
fn load_streams() -> Vec<StreamWorkload> {
    read_data_dir(&["ndjson", "jsonl"])
        .into_iter()
        .map(|(name, source)| {
            let records = split_records(&source);
            StreamWorkload { name, source, records }
        })
        .filter(|workload| !workload.records.is_empty())
        .collect()
}

fn bench_data(c: &mut Criterion) {
    let workloads = load_docs();
    if workloads.is_empty() {
        return;
    }
    // One arena, reused (reset, not freed) across every file and iteration.
    let arena = BumpArena::with_capacity(ARENA_BYTES);
    let mut group = c.benchmark_group("parse-data");
    for workload in &workloads {
        let source = &workload.source;
        group.throughput(Throughput::Bytes(source.len() as u64));
        bench_jsontape_global(&mut group, &workload.name, source);
        // The flagship configurations: parse into a reused bump arena, so no run touches the global allocator.
        // `owned-arena` is a decoded DOM in the arena; `view-arena` keeps zero-copy spans in the arena.
        group.bench_function(BenchmarkId::new(JSONTAPE_OWNED_ARENA, &workload.name), |bench| {
            bench.iter(|| {
                arena.reset();
                black_box(parse_in(black_box(source), &arena).unwrap())
            })
        });
        group.bench_function(BenchmarkId::new(JSONTAPE_VIEW_ARENA, &workload.name), |bench| {
            bench.iter(|| {
                arena.reset();
                black_box(view_in(black_box(source), &arena).unwrap())
            })
        });
        bench_dom_peers(&mut group, &workload.name, source);
        // JSON5 is a superset of JSON, so the json5 crate parses these strict documents too — the row that prices
        // JsonTape's JSON5 support against the only other JSON5 parser in the ecosystem.
        bench_json5_crate(&mut group, &workload.name, source);
    }
    group.finish();
}

fn bench_ndjson(c: &mut Criterion) {
    let workloads = load_streams();
    if workloads.is_empty() {
        return;
    }
    // One arena reused across the whole record stream, reset between documents — the genuine "one arena, many
    // documents" case.
    let arena = BumpArena::with_capacity(ARENA_BYTES);
    let mut group = c.benchmark_group("parse-ndjson");
    for workload in &workloads {
        let source = &workload.source;
        let records = &workload.records;
        let total: usize = records.iter().map(|record| record.len()).sum();
        group.throughput(Throughput::Bytes(total as u64));
        group.bench_function(BenchmarkId::new(JSONTAPE_OWNED, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    black_box(parse(black_box(&source[record.clone()])).unwrap());
                }
            })
        });
        group.bench_function(BenchmarkId::new(JSONTAPE_VIEW_BOUND, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    black_box(view_bound(black_box(&source[record.clone()])).unwrap());
                }
            })
        });
        group.bench_function(BenchmarkId::new(JSONTAPE_VIEW, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    black_box(view(black_box(&source[record.clone()])).unwrap());
                }
            })
        });
        group.bench_function(BenchmarkId::new(JSONTAPE_OWNED_ARENA, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    arena.reset();
                    black_box(parse_in(black_box(&source[record.clone()]), &arena).unwrap());
                }
            })
        });
        group.bench_function(BenchmarkId::new(JSONTAPE_VIEW_ARENA, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    arena.reset();
                    black_box(view_in(black_box(&source[record.clone()]), &arena).unwrap());
                }
            })
        });
        group.bench_function(BenchmarkId::new(SERDE_OWNED, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    black_box(serde_json::from_slice::<serde_json::Value>(black_box(&source[record.clone()])).unwrap());
                }
            })
        });
        // simd-json mutates its input in place, so both rows restore the whole file into one reused buffer per
        // iteration, then parse each record's slice in place while sharing one set of scratch buffers across the stream
        // — the fair analogue to arena reuse.
        group.bench_function(BenchmarkId::new(SIMDJSON_OWNED, &workload.name), |bench| {
            let capacity = records.iter().map(|record| record.len()).max().unwrap_or(0);
            let mut buffers = simd_json::Buffers::new(capacity + 64);
            let mut whole = source.to_vec();
            bench.iter(|| {
                whole.copy_from_slice(black_box(source));
                for record in records {
                    let slice = &mut whole[record.clone()];
                    black_box(simd_json::to_owned_value_with_buffers(slice, &mut buffers).unwrap());
                }
            })
        });
        group.bench_function(BenchmarkId::new(SIMDJSON_BORROWED, &workload.name), |bench| {
            let capacity = records.iter().map(|record| record.len()).max().unwrap_or(0);
            let mut buffers = simd_json::Buffers::new(capacity + 64);
            let mut whole = source.to_vec();
            bench.iter(|| {
                whole.copy_from_slice(black_box(source));
                for record in records {
                    let slice = &mut whole[record.clone()];
                    black_box(simd_json::to_borrowed_value_with_buffers(slice, &mut buffers).unwrap());
                }
            })
        });
        // JSON5 is a superset of JSON, so the json5 crate parses these records too.
        group.bench_function(BenchmarkId::new(JSON5_OWNED, &workload.name), |bench| {
            bench.iter(|| {
                for record in records {
                    let text = core::str::from_utf8(black_box(&source[record.clone()])).unwrap();
                    black_box(json5::from_str::<serde_json::Value>(text).unwrap());
                }
            })
        });
    }
    group.finish();
}

criterion_group!(
    benches,
    bench_strict_parse,
    bench_json5_parse,
    bench_serialize,
    bench_data,
    bench_ndjson
);
criterion_main!(benches);