datavalue-rs 0.2.3

Bump-allocated JSON value type with a built-in zero-copy parser and serde_json-style access API.
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Native JSON emitter for [`DataValue`] and [`OwnedDataValue`].
//!
//! Bypasses the `serde_json::to_string` path. The serde route pays trait
//! dispatch per node and a per-byte string-escape loop; emitting directly
//! into a buffer with `ryu` / `itoa` and a SWAR-driven escape scan lands
//! closer to the bespoke emitters in `json-rust` / `simd_json`.
//!
//! The same writers feed three sinks — `Vec<u8>` for [`DataValue::write_json_into`],
//! `fmt::Formatter` for the [`fmt::Display`] impls, and an indenting wrapper
//! for [`DataValue::pretty`] — through the [`JsonSink`] trait below.
//!
//! The `Serialize` impl in [`crate::ser`] is still the right entry point
//! when feeding non-JSON serde sinks (msgpack, flexbuffers, etc.).

use core::fmt;

use crate::number::NumberValue;
use crate::owned::OwnedDataValue;
use crate::value::DataValue;

/// Sink abstraction over `Vec<u8>` and `fmt::Formatter`. Bytes pushed are
/// always valid UTF-8 (numbers are ASCII; strings are passed through from
/// `&str` sources; escapes are ASCII), so the str adapter is sound.
///
/// Contract: every `write_bytes` call passes a *complete* valid-UTF-8 chunk
/// (string runs are sliced at escape hits, which are ASCII, so run boundaries
/// are char boundaries; everything else written is ASCII). `FormatterSink`'s
/// staging buffer relies on this — it never splits a chunk, so the buffer
/// content is always a concatenation of whole chunks and stays valid UTF-8.
pub(crate) trait JsonSink {
    type Error;
    fn write_bytes(&mut self, b: &[u8]) -> Result<(), Self::Error>;
    fn write_byte(&mut self, b: u8) -> Result<(), Self::Error>;
}

impl JsonSink for Vec<u8> {
    type Error = core::convert::Infallible;
    #[inline]
    fn write_bytes(&mut self, b: &[u8]) -> Result<(), Self::Error> {
        self.extend_from_slice(b);
        Ok(())
    }
    #[inline]
    fn write_byte(&mut self, b: u8) -> Result<(), Self::Error> {
        self.push(b);
        Ok(())
    }
}

impl JsonSink for bumpalo::collections::Vec<'_, u8> {
    type Error = core::convert::Infallible;
    #[inline]
    fn write_bytes(&mut self, b: &[u8]) -> Result<(), Self::Error> {
        // Not extend_from_slice: bumpalo's Vec is a pre-specialization std
        // fork, so its extend_from_slice copies element-by-element through a
        // cloned iterator (measured ~2x slower on string-heavy emit). Reserve
        // once and memcpy.
        self.reserve(b.len());
        let len = self.len();
        // SAFETY: `reserve` guarantees capacity for `len + b.len()`; the
        // source and destination don't overlap (`b` borrows input strings or
        // static tables, never this vec's buffer).
        unsafe {
            core::ptr::copy_nonoverlapping(b.as_ptr(), self.as_mut_ptr().add(len), b.len());
            self.set_len(len + b.len());
        }
        Ok(())
    }
    #[inline]
    fn write_byte(&mut self, b: u8) -> Result<(), Self::Error> {
        self.push(b);
        Ok(())
    }
}

/// Finish an arena emit: reclaim unused BumpVec capacity, then reinterpret
/// the bytes as `&str`.
///
/// SAFETY (of the contained `from_utf8_unchecked`): the emitters only write
/// valid UTF-8 — ASCII structural bytes/escapes/numbers and `&str` payload
/// runs (see the `JsonSink` contract).
#[inline]
fn into_arena_str<'b>(mut out: bumpalo::collections::Vec<'b, u8>) -> &'b str {
    // Trim growth slack. The vec is the arena's most recent allocation
    // (emitting allocates nothing else), so bumpalo reclaims in place;
    // measured cost is noise-level because it only copies when more than
    // half the capacity would be reclaimed.
    out.shrink_to_fit();
    unsafe { core::str::from_utf8_unchecked(out.into_bump_slice()) }
}

/// Staging capacity for `FormatterSink`. Without it, every structural byte
/// (`[ ] { } , : "`) would be its own virtual `fmt::Write::write_str` call;
/// with it, output reaches the formatter in ~128-byte runs.
const FMT_STAGING: usize = 128;

struct FormatterSink<'a, 'b> {
    f: &'a mut fmt::Formatter<'b>,
    buf: [u8; FMT_STAGING],
    len: usize,
}

impl<'a, 'b> FormatterSink<'a, 'b> {
    fn new(f: &'a mut fmt::Formatter<'b>) -> Self {
        FormatterSink {
            f,
            buf: [0; FMT_STAGING],
            len: 0,
        }
    }

    fn flush(&mut self) -> fmt::Result {
        if self.len > 0 {
            // SAFETY: the buffer holds a concatenation of complete chunks,
            // each valid UTF-8 (see the JsonSink contract); chunks are never
            // split across flushes.
            let s = unsafe { core::str::from_utf8_unchecked(&self.buf[..self.len]) };
            self.f.write_str(s)?;
            self.len = 0;
        }
        Ok(())
    }
}

impl<'a, 'b> JsonSink for FormatterSink<'a, 'b> {
    type Error = fmt::Error;
    #[inline]
    fn write_bytes(&mut self, b: &[u8]) -> Result<(), Self::Error> {
        if self.len + b.len() > FMT_STAGING {
            self.flush()?;
            if b.len() >= FMT_STAGING {
                // SAFETY: chunks are complete valid UTF-8 (JsonSink contract).
                let s = unsafe { core::str::from_utf8_unchecked(b) };
                return self.f.write_str(s);
            }
        }
        self.buf[self.len..self.len + b.len()].copy_from_slice(b);
        self.len += b.len();
        Ok(())
    }
    #[inline]
    fn write_byte(&mut self, b: u8) -> Result<(), Self::Error> {
        debug_assert!(b.is_ascii());
        if self.len == FMT_STAGING {
            self.flush()?;
        }
        self.buf[self.len] = b;
        self.len += 1;
        Ok(())
    }
}

#[inline]
fn write_escaped_str<S: JsonSink>(out: &mut S, s: &str) -> Result<(), S::Error> {
    out.write_byte(b'"')?;
    let bytes = s.as_bytes();
    let mut run_start = 0;

    // Scan-and-copy runs between escapes. The scan is the shared
    // `crate::simd` helper: SWAR for slices under 32 bytes (the typical
    // short JSON string — its criteria and mask are identical to the old
    // inlined loop), the 16-byte SIMD stride for longer ones.
    while let Some(off) = crate::simd::find_string_terminator(&bytes[run_start..]) {
        let hit = run_start + off;
        if hit > run_start {
            out.write_bytes(&bytes[run_start..hit])?;
        }
        write_escape_byte(out, bytes[hit])?;
        run_start = hit + 1;
    }
    if run_start < bytes.len() {
        out.write_bytes(&bytes[run_start..])?;
    }
    out.write_byte(b'"')
}

/// DateTime arm: the 20-byte ISO buffer is pure ASCII with no JSON-special
/// bytes, so it goes to the sink as quote + raw bytes + quote — no heap
/// `String`, no escape scan. Years outside 0..=9999 fall back to chrono's
/// RFC3339 formatter (heap) through the escaped path.
#[cfg(feature = "datetime")]
fn write_datetime<S: JsonSink>(
    out: &mut S,
    d: &crate::datetime::DataDateTime,
) -> Result<(), S::Error> {
    match d.iso_secs_buf() {
        Some(buf) => {
            out.write_byte(b'"')?;
            out.write_bytes(&buf)?;
            out.write_byte(b'"')
        }
        None => write_escaped_str(out, &d.to_iso_string()),
    }
}

/// Duration arm: `Xd:Xh:Xm:Xs` is digits, `-`, letters, and `:` — never
/// escaped, so it streams via itoa without the intermediate `String`.
#[cfg(feature = "datetime")]
fn write_duration<S: JsonSink>(
    out: &mut S,
    d: &crate::datetime::DataDuration,
) -> Result<(), S::Error> {
    let (days, hours, minutes, seconds) = d.dhms();
    let mut b = itoa::Buffer::new();
    out.write_byte(b'"')?;
    out.write_bytes(b.format(days).as_bytes())?;
    out.write_bytes(b"d:")?;
    out.write_bytes(b.format(hours).as_bytes())?;
    out.write_bytes(b"h:")?;
    out.write_bytes(b.format(minutes).as_bytes())?;
    out.write_bytes(b"m:")?;
    out.write_bytes(b.format(seconds).as_bytes())?;
    out.write_bytes(b"s\"")
}

#[inline]
fn write_escape_byte<S: JsonSink>(out: &mut S, b: u8) -> Result<(), S::Error> {
    match b {
        b'"' => out.write_bytes(b"\\\""),
        b'\\' => out.write_bytes(b"\\\\"),
        b'\n' => out.write_bytes(b"\\n"),
        b'\r' => out.write_bytes(b"\\r"),
        b'\t' => out.write_bytes(b"\\t"),
        0x08 => out.write_bytes(b"\\b"),
        0x0C => out.write_bytes(b"\\f"),
        c => {
            // Other control bytes (< 0x20 not named above) use \u00XX. The
            // high byte is always 0 here.
            const HEX: &[u8; 16] = b"0123456789abcdef";
            out.write_bytes(b"\\u00")?;
            out.write_byte(HEX[((c >> 4) & 0x0F) as usize])?;
            out.write_byte(HEX[(c & 0x0F) as usize])
        }
    }
}

#[inline]
fn write_number<S: JsonSink>(out: &mut S, n: NumberValue) -> Result<(), S::Error> {
    match n {
        NumberValue::Integer(i) => {
            let mut buf = itoa::Buffer::new();
            out.write_bytes(buf.format(i).as_bytes())
        }
        NumberValue::Float(f) => {
            if !f.is_finite() {
                // serde_json emits non-finite floats as `null` to keep
                // output valid JSON. Match that.
                return out.write_bytes(b"null");
            }
            let mut buf = ryu::Buffer::new();
            out.write_bytes(buf.format_finite(f).as_bytes())
        }
    }
}

// ---- Compact emit (no whitespace) ------------------------------------------------

fn write_data_value<S: JsonSink>(out: &mut S, v: &DataValue<'_>) -> Result<(), S::Error> {
    match *v {
        DataValue::Null => out.write_bytes(b"null"),
        DataValue::Bool(true) => out.write_bytes(b"true"),
        DataValue::Bool(false) => out.write_bytes(b"false"),
        DataValue::Number(n) => write_number(out, n),
        DataValue::String(s) => write_escaped_str(out, s),
        DataValue::Array(items) => {
            out.write_byte(b'[')?;
            let mut first = true;
            for item in items {
                if !first {
                    out.write_byte(b',')?;
                }
                first = false;
                write_data_value(out, item)?;
            }
            out.write_byte(b']')
        }
        DataValue::Object(pairs) => {
            out.write_byte(b'{')?;
            let mut first = true;
            for (k, v) in pairs {
                if !first {
                    out.write_byte(b',')?;
                }
                first = false;
                write_escaped_str(out, k)?;
                out.write_byte(b':')?;
                write_data_value(out, v)?;
            }
            out.write_byte(b'}')
        }
        #[cfg(feature = "datetime")]
        DataValue::DateTime(d) => write_datetime(out, &d),
        #[cfg(feature = "datetime")]
        DataValue::Duration(d) => write_duration(out, &d),
    }
}

fn write_owned_value<S: JsonSink>(out: &mut S, v: &OwnedDataValue) -> Result<(), S::Error> {
    match v {
        OwnedDataValue::Null => out.write_bytes(b"null"),
        OwnedDataValue::Bool(true) => out.write_bytes(b"true"),
        OwnedDataValue::Bool(false) => out.write_bytes(b"false"),
        OwnedDataValue::Number(n) => write_number(out, *n),
        OwnedDataValue::String(s) => write_escaped_str(out, s),
        OwnedDataValue::Array(items) => {
            out.write_byte(b'[')?;
            let mut first = true;
            for item in items {
                if !first {
                    out.write_byte(b',')?;
                }
                first = false;
                write_owned_value(out, item)?;
            }
            out.write_byte(b']')
        }
        OwnedDataValue::Object(pairs) => {
            out.write_byte(b'{')?;
            let mut first = true;
            for (k, v) in pairs {
                if !first {
                    out.write_byte(b',')?;
                }
                first = false;
                write_escaped_str(out, k)?;
                out.write_byte(b':')?;
                write_owned_value(out, v)?;
            }
            out.write_byte(b'}')
        }
        #[cfg(feature = "datetime")]
        OwnedDataValue::DateTime(d) => write_datetime(out, d),
        #[cfg(feature = "datetime")]
        OwnedDataValue::Duration(d) => write_duration(out, d),
    }
}

// ---- Pretty emit (two-space indent, matches serde_json::to_string_pretty) -------

#[inline]
fn write_indent<S: JsonSink>(out: &mut S, depth: usize) -> Result<(), S::Error> {
    // Two spaces per level. Keep a reasonably long literal so most depths
    // need a single write.
    const SPACES: &[u8; 64] = b"                                                                ";
    let mut remaining = depth * 2;
    while remaining > 0 {
        let chunk = remaining.min(SPACES.len());
        out.write_bytes(&SPACES[..chunk])?;
        remaining -= chunk;
    }
    Ok(())
}

fn write_data_value_pretty<S: JsonSink>(
    out: &mut S,
    v: &DataValue<'_>,
    depth: usize,
) -> Result<(), S::Error> {
    match *v {
        DataValue::Null => out.write_bytes(b"null"),
        DataValue::Bool(true) => out.write_bytes(b"true"),
        DataValue::Bool(false) => out.write_bytes(b"false"),
        DataValue::Number(n) => write_number(out, n),
        DataValue::String(s) => write_escaped_str(out, s),
        DataValue::Array(items) => {
            if items.is_empty() {
                return out.write_bytes(b"[]");
            }
            out.write_byte(b'[')?;
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.write_byte(b',')?;
                }
                out.write_byte(b'\n')?;
                write_indent(out, depth + 1)?;
                write_data_value_pretty(out, item, depth + 1)?;
            }
            out.write_byte(b'\n')?;
            write_indent(out, depth)?;
            out.write_byte(b']')
        }
        DataValue::Object(pairs) => {
            if pairs.is_empty() {
                return out.write_bytes(b"{}");
            }
            out.write_byte(b'{')?;
            for (i, (k, v)) in pairs.iter().enumerate() {
                if i > 0 {
                    out.write_byte(b',')?;
                }
                out.write_byte(b'\n')?;
                write_indent(out, depth + 1)?;
                write_escaped_str(out, k)?;
                out.write_bytes(b": ")?;
                write_data_value_pretty(out, v, depth + 1)?;
            }
            out.write_byte(b'\n')?;
            write_indent(out, depth)?;
            out.write_byte(b'}')
        }
        #[cfg(feature = "datetime")]
        DataValue::DateTime(d) => write_datetime(out, &d),
        #[cfg(feature = "datetime")]
        DataValue::Duration(d) => write_duration(out, &d),
    }
}

fn write_owned_value_pretty<S: JsonSink>(
    out: &mut S,
    v: &OwnedDataValue,
    depth: usize,
) -> Result<(), S::Error> {
    match v {
        OwnedDataValue::Null => out.write_bytes(b"null"),
        OwnedDataValue::Bool(true) => out.write_bytes(b"true"),
        OwnedDataValue::Bool(false) => out.write_bytes(b"false"),
        OwnedDataValue::Number(n) => write_number(out, *n),
        OwnedDataValue::String(s) => write_escaped_str(out, s),
        OwnedDataValue::Array(items) => {
            if items.is_empty() {
                return out.write_bytes(b"[]");
            }
            out.write_byte(b'[')?;
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.write_byte(b',')?;
                }
                out.write_byte(b'\n')?;
                write_indent(out, depth + 1)?;
                write_owned_value_pretty(out, item, depth + 1)?;
            }
            out.write_byte(b'\n')?;
            write_indent(out, depth)?;
            out.write_byte(b']')
        }
        OwnedDataValue::Object(pairs) => {
            if pairs.is_empty() {
                return out.write_bytes(b"{}");
            }
            out.write_byte(b'{')?;
            for (i, (k, v)) in pairs.iter().enumerate() {
                if i > 0 {
                    out.write_byte(b',')?;
                }
                out.write_byte(b'\n')?;
                write_indent(out, depth + 1)?;
                write_escaped_str(out, k)?;
                out.write_bytes(b": ")?;
                write_owned_value_pretty(out, v, depth + 1)?;
            }
            out.write_byte(b'\n')?;
            write_indent(out, depth)?;
            out.write_byte(b'}')
        }
        #[cfg(feature = "datetime")]
        OwnedDataValue::DateTime(d) => write_datetime(out, d),
        #[cfg(feature = "datetime")]
        OwnedDataValue::Duration(d) => write_duration(out, d),
    }
}

// ---- Public API on DataValue ---------------------------------------------------

impl DataValue<'_> {
    /// Append the compact JSON encoding of this value to `out`. Useful when
    /// you want to amortize allocation across many values into a shared buffer.
    /// For one-shot string conversion, use the [`fmt::Display`] impl
    /// (`v.to_string()` / `format!("{v}")` / `println!("{v}")`).
    pub fn write_json_into(&self, out: &mut Vec<u8>) {
        let _ = write_data_value(out, self);
    }

    /// Pretty-print wrapper. `format!("{}", v.pretty())` produces the same
    /// two-space-indented layout as `serde_json::to_string_pretty`.
    ///
    /// ```
    /// use bumpalo::Bump;
    /// use datavalue_rs::DataValue;
    ///
    /// let arena = Bump::new();
    /// let v = DataValue::from_str(r#"{"a":1}"#, &arena).unwrap();
    /// assert_eq!(v.pretty().to_string(), "{\n  \"a\": 1\n}");
    /// ```
    pub fn pretty(&self) -> Pretty<'_, DataValue<'_>> {
        Pretty(self)
    }

    /// Append the pretty JSON encoding of this value to `out`.
    pub fn write_json_pretty_into(&self, out: &mut Vec<u8>) {
        let _ = write_data_value_pretty(out, self, 0);
    }

    /// Emit the compact JSON encoding directly into `arena` and return the
    /// arena-resident string — no heap allocation. The single-copy path for
    /// consumers that render values to text living alongside the values
    /// (e.g. a `&str` result slot in the same evaluation arena).
    ///
    /// ```
    /// use bumpalo::Bump;
    /// use datavalue_rs::DataValue;
    ///
    /// let arena = Bump::new();
    /// let v = DataValue::from_str(r#"{"a":[1,2.5,"hi"]}"#, &arena).unwrap();
    /// let s: &str = v.to_json_str_in(&arena);
    /// assert_eq!(s, r#"{"a":[1,2.5,"hi"]}"#);
    /// ```
    pub fn to_json_str_in<'b>(&self, arena: &'b bumpalo::Bump) -> &'b str {
        let mut out = bumpalo::collections::Vec::new_in(arena);
        let _ = write_data_value(&mut out, self);
        into_arena_str(out)
    }

    /// Pretty sibling of [`DataValue::to_json_str_in`].
    pub fn to_json_pretty_str_in<'b>(&self, arena: &'b bumpalo::Bump) -> &'b str {
        let mut out = bumpalo::collections::Vec::new_in(arena);
        let _ = write_data_value_pretty(&mut out, self, 0);
        into_arena_str(out)
    }
}

impl OwnedDataValue {
    /// Append the compact JSON encoding of this value to `out`. See
    /// [`DataValue::write_json_into`]; this is the owned-side mirror.
    pub fn write_json_into(&self, out: &mut Vec<u8>) {
        let _ = write_owned_value(out, self);
    }

    /// Pretty-print wrapper; see [`DataValue::pretty`].
    ///
    /// ```
    /// use datavalue_rs::OwnedDataValue;
    ///
    /// let v: OwnedDataValue = r#"{"a":1}"#.parse().unwrap();
    /// assert_eq!(v.pretty().to_string(), "{\n  \"a\": 1\n}");
    /// ```
    pub fn pretty(&self) -> Pretty<'_, OwnedDataValue> {
        Pretty(self)
    }

    /// Append the pretty JSON encoding of this value to `out`.
    pub fn write_json_pretty_into(&self, out: &mut Vec<u8>) {
        let _ = write_owned_value_pretty(out, self, 0);
    }

    /// Emit the compact JSON encoding directly into `arena`; see
    /// [`DataValue::to_json_str_in`]. This is the owned-side mirror.
    pub fn to_json_str_in<'b>(&self, arena: &'b bumpalo::Bump) -> &'b str {
        let mut out = bumpalo::collections::Vec::new_in(arena);
        let _ = write_owned_value(&mut out, self);
        into_arena_str(out)
    }

    /// Pretty sibling of [`OwnedDataValue::to_json_str_in`].
    pub fn to_json_pretty_str_in<'b>(&self, arena: &'b bumpalo::Bump) -> &'b str {
        let mut out = bumpalo::collections::Vec::new_in(arena);
        let _ = write_owned_value_pretty(&mut out, self, 0);
        into_arena_str(out)
    }
}

// ---- Display + Pretty wrapper ---------------------------------------------------

/// Wrapper produced by [`DataValue::pretty`] / [`OwnedDataValue::pretty`] that
/// renders the value as indented JSON via `Display`.
pub struct Pretty<'b, T: ?Sized>(&'b T);

impl fmt::Display for DataValue<'_> {
    /// Compact JSON. Same shape as `serde_json::to_string`.
    ///
    /// ```
    /// use bumpalo::Bump;
    /// use datavalue_rs::DataValue;
    ///
    /// let arena = Bump::new();
    /// let v = DataValue::from_str(r#"{"a":[1,2.5,"hi"]}"#, &arena).unwrap();
    /// assert_eq!(v.to_string(), r#"{"a":[1,2.5,"hi"]}"#);
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut sink = FormatterSink::new(f);
        write_data_value(&mut sink, self)?;
        sink.flush()
    }
}

impl fmt::Display for OwnedDataValue {
    /// Compact JSON. Same shape as `serde_json::to_string`.
    ///
    /// ```
    /// use datavalue_rs::OwnedDataValue;
    ///
    /// let v: OwnedDataValue = r#"{"a":[1,2.5,"hi"]}"#.parse().unwrap();
    /// assert_eq!(v.to_string(), r#"{"a":[1,2.5,"hi"]}"#);
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut sink = FormatterSink::new(f);
        write_owned_value(&mut sink, self)?;
        sink.flush()
    }
}

impl fmt::Display for Pretty<'_, DataValue<'_>> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut sink = FormatterSink::new(f);
        write_data_value_pretty(&mut sink, self.0, 0)?;
        sink.flush()
    }
}

impl fmt::Display for Pretty<'_, OwnedDataValue> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut sink = FormatterSink::new(f);
        write_owned_value_pretty(&mut sink, self.0, 0)?;
        sink.flush()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bumpalo::Bump;

    fn round_trip(s: &str) -> String {
        let arena = Bump::new();
        let v = DataValue::from_str(s, &arena).unwrap();
        v.to_string()
    }

    #[test]
    fn primitives() {
        assert_eq!(round_trip("null"), "null");
        assert_eq!(round_trip("true"), "true");
        assert_eq!(round_trip("false"), "false");
        assert_eq!(round_trip("42"), "42");
        assert_eq!(round_trip("-7"), "-7");
        assert_eq!(round_trip("3.5"), "3.5");
    }

    #[test]
    fn strings_with_escapes() {
        assert_eq!(round_trip(r#""hello""#), r#""hello""#);
        assert_eq!(round_trip(r#""a\nb""#), r#""a\nb""#);
        assert_eq!(round_trip(r#""a\\b""#), r#""a\\b""#);
        assert_eq!(round_trip(r#""a\"b""#), r#""a\"b""#);
        // Unicode passes through verbatim (we don't re-escape non-ASCII).
        assert_eq!(round_trip(r#""café""#), r#""café""#);
    }

    #[test]
    fn control_bytes_render_as_unicode_escapes() {
        let arena = Bump::new();
        let v = DataValue::from_str("\"\\u0001\"", &arena).unwrap();
        assert_eq!(v.to_string(), "\"\\u0001\"");
    }

    #[test]
    fn nested_round_trip_matches_serde_json() {
        let input = r#"{"a":[1,2,{"b":"hi\n","c":null,"d":true}],"e":-3.5,"f":[],"g":{}}"#;
        let arena = Bump::new();
        let v = DataValue::from_str(input, &arena).unwrap();
        let ours = v.to_string();
        let serde: serde_json::Value = serde_json::from_str(input).unwrap();
        let theirs = serde_json::to_string(&serde).unwrap();
        assert_eq!(ours, theirs);
    }

    #[test]
    fn long_string_swar_path() {
        let arena = Bump::new();
        let s = format!("\"{}\"", "x".repeat(200));
        let v = DataValue::from_str(&s, &arena).unwrap();
        assert_eq!(v.to_string(), s);
    }

    // Display goes through FormatterSink's staging buffer; write_json_into
    // goes straight to the Vec. The two must be byte-identical for every
    // buffering edge case: chunks that straddle the FMT_STAGING boundary,
    // chunks larger than the buffer (direct-write path), multi-byte UTF-8
    // near flush points, and escape-heavy strings (many tiny chunks).
    fn assert_display_matches_vec(input: &str) {
        let arena = Bump::new();
        let v = DataValue::from_str(input, &arena).unwrap();
        let mut buf = Vec::new();
        v.write_json_into(&mut buf);
        assert_eq!(v.to_string().into_bytes(), buf, "compact mismatch");

        let mut pretty_buf = Vec::new();
        v.write_json_pretty_into(&mut pretty_buf);
        assert_eq!(
            v.pretty().to_string().into_bytes(),
            pretty_buf,
            "pretty mismatch"
        );
    }

    #[cfg(feature = "datetime")]
    #[test]
    fn datetime_emit_matches_display_wire_format() {
        use crate::datetime::DataDateTime;

        let dt = DataDateTime::parse("2024-01-15T12:30:45Z").unwrap();
        let later = DataDateTime::parse("2024-01-18T16:35:51Z").unwrap();
        let du = later.diff(&dt);

        for v in [DataValue::DateTime(dt), DataValue::Duration(du)] {
            let display = v.to_string();
            let mut buf = Vec::new();
            v.write_json_into(&mut buf);
            assert_eq!(display.into_bytes(), buf);

            let owned = v.to_owned();
            assert_eq!(owned.to_string(), v.to_string());
        }
        assert_eq!(
            DataValue::DateTime(dt).to_string(),
            "\"2024-01-15T12:30:45Z\""
        );
        assert_eq!(DataValue::Duration(du).to_string(), "\"3d:4h:5m:6s\"");
    }

    #[test]
    fn to_json_str_in_matches_to_string() {
        let inputs = [
            "null",
            "[]",
            r#"{"a":[1,2.5,"hi\n",null,true],"b":{"c":"é€"},"e":-0.125}"#,
        ];
        let arena = Bump::new();
        // Emit into a *different* arena than the values live in.
        let out_arena = Bump::new();
        for input in inputs {
            let v = DataValue::from_str(input, &arena).unwrap();
            assert_eq!(v.to_json_str_in(&out_arena), v.to_string());
            assert_eq!(v.to_json_pretty_str_in(&out_arena), v.pretty().to_string());

            let owned = v.to_owned();
            assert_eq!(owned.to_json_str_in(&out_arena), owned.to_string());
            assert_eq!(
                owned.to_json_pretty_str_in(&out_arena),
                owned.pretty().to_string()
            );
        }
        // Long string: forces BumpVec growth inside the emit.
        let long = format!("\"{}\"", "x".repeat(5000));
        let v = DataValue::from_str(&long, &arena).unwrap();
        assert_eq!(v.to_json_str_in(&out_arena), long);
    }

    #[test]
    fn display_matches_vec_across_staging_boundaries() {
        // ASCII strings sized to land runs on every offset around the
        // 128-byte staging capacity.
        for n in [1, 7, 126, 127, 128, 129, 200, 255, 256, 257, 1000] {
            assert_display_matches_vec(&format!("\"{}\"", "x".repeat(n)));
        }
        // Multi-byte UTF-8 (2- and 3-byte chars) filling past the boundary —
        // a split inside a char would corrupt output or trip UTF-8 checks.
        for n in [60, 63, 64, 65, 100] {
            assert_display_matches_vec(&format!("\"{}\"", "é".repeat(n)));
            assert_display_matches_vec(&format!("\"{}\"", "".repeat(n)));
        }
        // Escape-heavy: alternating escapes chop the string into 1-byte runs.
        assert_display_matches_vec(&format!("\"{}\"", r#"a\n"#.repeat(100)));
        // Composite document with many small structural writes.
        assert_display_matches_vec(
            r#"{"a":[1,2.5,"hi\n",null,true],"b":{"c":"é€","d":[[],{}]},"e":-0.125}"#,
        );
    }

    #[test]
    fn non_finite_floats_render_as_null() {
        let v = DataValue::from_f64(f64::NAN);
        assert_eq!(v.to_string(), "null");
        let v = DataValue::from_f64(f64::INFINITY);
        assert_eq!(v.to_string(), "null");
    }

    #[test]
    fn owned_round_trip() {
        let v: OwnedDataValue = r#"{"name":"alice","age":30}"#.parse().unwrap();
        let serde: serde_json::Value = serde_json::from_str(&v.to_string()).unwrap();
        assert_eq!(serde["name"], "alice");
        assert_eq!(serde["age"], 30);
    }

    #[test]
    fn write_json_into_buffer() {
        let arena = Bump::new();
        let v = DataValue::from_str(r#"[1,2,3]"#, &arena).unwrap();
        let mut buf = Vec::new();
        v.write_json_into(&mut buf);
        assert_eq!(buf, b"[1,2,3]");
    }

    #[test]
    fn pretty_matches_serde_json_pretty() {
        let input = r#"{"a":[1,2,{"b":"hi","c":null}],"e":-3.5,"f":[],"g":{}}"#;
        let arena = Bump::new();
        let v = DataValue::from_str(input, &arena).unwrap();
        let ours = v.pretty().to_string();
        let serde: serde_json::Value = serde_json::from_str(input).unwrap();
        let theirs = serde_json::to_string_pretty(&serde).unwrap();
        assert_eq!(ours, theirs);
    }

    #[test]
    fn pretty_owned_matches_serde_json_pretty() {
        let input = r#"{"a":[1,2,{"b":"hi","c":null}],"e":-3.5,"f":[],"g":{}}"#;
        let v: OwnedDataValue = input.parse().unwrap();
        let serde: serde_json::Value = serde_json::from_str(input).unwrap();
        assert_eq!(
            v.pretty().to_string(),
            serde_json::to_string_pretty(&serde).unwrap()
        );
    }

    #[test]
    fn pretty_empty_collections_inline() {
        let arena = Bump::new();
        let v = DataValue::from_str(r#"{"a":[],"b":{}}"#, &arena).unwrap();
        assert_eq!(v.pretty().to_string(), "{\n  \"a\": [],\n  \"b\": {}\n}");
    }

    #[test]
    fn pretty_deep_indent_beyond_64_spaces() {
        // 35 levels deep -> 70 spaces of indent on the leaf line. Exercises
        // the chunked SPACES write loop.
        let arena = Bump::new();
        let mut s = String::new();
        for _ in 0..35 {
            s.push('[');
        }
        s.push('1');
        for _ in 0..35 {
            s.push(']');
        }
        let v = DataValue::from_str(&s, &arena).unwrap();
        let ours = v.pretty().to_string();
        let serde: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(ours, serde_json::to_string_pretty(&serde).unwrap());
    }
}