jshift 0.7.0

Schema-guided typed JSON on raw bytes: path get/mutate, open views, project — without a Value tree.
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
//! Enum tagging on raw JSON (serde-compatible shapes, no `Value` tree).
//!
//! | Style | Unit | Struct / newtype | Derive |
//! | --- | --- | --- | --- |
//! | **External** (default) | `"Ready"` | `{"Click":{…}}` / `{"Id":7}` | `#[derive(JsonView)]` |
//! | **Internal** | `{"type":"Ready"}` | `{"type":"Click","x":1}` | `#[json(tag = "type")]` |
//! | **Adjacent** | `{"t":"Ready"}` | `{"t":"Click","c":{…}}` | `#[json(tag = "t", content = "c")]` |
//! | **Untagged** | try in order | try in order | `#[json(untagged)]` |
//!
//! # Design (byte-level)
//!
//! * **External unit** tags are a JSON string; unescaped ASCII is zero-copy `&str`.
//! * **External object** tags are a **single-member** object (payload span borrowed).
//! * **Internal** reads a string field (`tag` key) then treats the **same object**
//!   as the field bag (struct) or unit (tag only).
//! * **Adjacent** reads `tag` + optional `content` keys on one object.
//! * **Untagged** tries caller-supplied decoders in order (first `Ok` wins).
//! * Trailing junk after the value is rejected (whitespace-only allowed).
//!
//! # Hand-written vs derive
//!
//! ```
//! use jshift::{read_external_unit, write_external_unit};
//!
//! #[derive(Debug, PartialEq)]
//! enum Status { Ready, Done }
//!
//! let s = read_external_unit(br#""Ready""#, |n| match n {
//!     "Ready" => Some(Status::Ready),
//!     "Done" => Some(Status::Done),
//!     _ => None,
//! }).unwrap();
//! assert_eq!(s, Status::Ready);
//!
//! let mut out = Vec::new();
//! write_external_unit(&mut out, "Done");
//! assert_eq!(out, br#""Done""#);
//! ```
//!
//! See also the crate [API guide](crate::api_guide) for when enums fit vs path views.

use std::borrow::Cow;

use crate::error::Error;
use crate::path::PathSegment;
use crate::scan::{find_string_end, find_value, skip_value, skip_whitespace};
use crate::view::JsonView;

/// Decode an externally tagged **unit** enum as a JSON string.
///
/// `match_name` receives the **decoded** string content (escapes applied when
/// present). Return `Some(T)` for a known variant, `None` for unknown.
///
/// # Errors
///
/// * [`Error::TypeMismatch`] — root is not a string.
/// * [`Error::Decode`] — unknown variant name.
/// * [`Error::InvalidJsonSyntax`] — malformed string or trailing non-ws data.
#[inline]
pub fn read_external_unit<T, F>(json: &[u8], mut match_name: F) -> Result<T, Error>
where
    F: FnMut(&str) -> Option<T>,
{
    let start = skip_whitespace(json, 0);
    if start >= json.len() || json[start] != b'"' {
        return Err(Error::TypeMismatch {
            expected: "string (unit enum)",
            found: type_hint(json, start),
        });
    }
    let content_start = start + 1;
    let end_q = find_string_end(json, content_start)?;
    let raw = &json[content_start..end_q];
    let after = end_q + 1;
    ensure_only_trailing_ws(json, after)?;

    if !raw.contains(&b'\\') {
        let name = std::str::from_utf8(raw).map_err(|_| Error::TypeMismatch {
            expected: "utf-8 string",
            found: "invalid utf-8",
        })?;
        return match_name(name).ok_or_else(|| Error::Decode {
            path: name.to_string(),
            expected: "known unit variant",
            found: "unknown variant",
            pos: Some(start),
        });
    }

    let lit = &json[start..=end_q];
    let s = crate::convert::from_json_string(lit).ok_or(Error::TypeMismatch {
        expected: "string",
        found: "invalid escape",
    })?;
    match_name(&s).ok_or(Error::Decode {
        path: s,
        expected: "known unit variant",
        found: "unknown variant",
        pos: Some(start),
    })
}

/// Zero-copy peek of an externally tagged object: `{"VariantName": <payload>}`.
///
/// Requires **exactly one** top-level object member. The returned
/// [`ExternalTag::payload`] is a subslice of `json` (no copy).
///
/// # Errors
///
/// Empty object, multi-key object, non-object root, syntax errors, trailing junk.
#[inline]
pub fn peek_external_object(json: &[u8]) -> Result<ExternalTag<'_>, Error> {
    let start = skip_whitespace(json, 0);
    if start >= json.len() || json[start] != b'{' {
        return Err(Error::TypeMismatch {
            expected: "object (externally tagged enum)",
            found: type_hint(json, start),
        });
    }
    let mut pos = skip_whitespace(json, start + 1);
    if pos >= json.len() || json[pos] == b'}' {
        return Err(Error::Decode {
            path: String::new(),
            expected: "one variant key",
            found: "empty object",
            pos: Some(pos),
        });
    }
    if json[pos] != b'"' {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Expected variant tag string",
        });
    }
    let ks = pos + 1;
    let ke = find_string_end(json, ks)?;
    let tag_raw = &json[ks..ke];
    pos = skip_whitespace(json, ke + 1);
    if pos >= json.len() || json[pos] != b':' {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Expected colon after enum tag",
        });
    }
    pos = skip_whitespace(json, pos + 1);
    let vs = pos;
    let ve = skip_value(json, vs)?;
    let payload = &json[vs..ve];
    pos = skip_whitespace(json, ve);
    if pos < json.len() && json[pos] == b',' {
        return Err(Error::Decode {
            path: String::new(),
            expected: "single-key external tag object",
            found: "multiple keys",
            pos: Some(pos),
        });
    }
    if pos >= json.len() || json[pos] != b'}' {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Expected closing brace after enum payload",
        });
    }
    ensure_only_trailing_ws(json, pos + 1)?;
    Ok(ExternalTag { tag_raw, payload })
}

/// Result of sniffing an externally tagged object: variant name + payload span.
///
/// Both fields borrow from the input buffer. Prefer [`tag_str`](Self::tag_str) or
/// [`tag_cow`](Self::tag_cow) over manual UTF-8 checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExternalTag<'a> {
    /// On-wire key content **between** quotes (may contain escape sequences).
    pub tag_raw: &'a [u8],
    /// Value span for the variant payload (includes nested structure as raw bytes).
    pub payload: &'a [u8],
}

impl<'a> ExternalTag<'a> {
    /// Tag as `&str` when the on-wire key has **no** escapes (common case).
    ///
    /// Returns an error if escapes are present — use [`tag_cow`](Self::tag_cow).
    #[inline]
    pub fn tag_str(&self) -> Result<&'a str, Error> {
        if self.tag_raw.contains(&b'\\') {
            return Err(Error::TypeMismatch {
                expected: "unescaped variant tag",
                found: "escaped tag",
            });
        }
        std::str::from_utf8(self.tag_raw).map_err(|_| Error::TypeMismatch {
            expected: "utf-8 tag",
            found: "invalid utf-8",
        })
    }

    /// Decode the tag with zero alloc when unescaped; owned `String` only if escaped.
    #[inline]
    pub fn tag_cow(&self) -> Result<Cow<'a, str>, Error> {
        if !self.tag_raw.contains(&b'\\') {
            let s = std::str::from_utf8(self.tag_raw).map_err(|_| Error::TypeMismatch {
                expected: "utf-8 tag",
                found: "invalid utf-8",
            })?;
            return Ok(Cow::Borrowed(s));
        }
        let mut lit = Vec::with_capacity(self.tag_raw.len() + 2);
        lit.push(b'"');
        lit.extend_from_slice(self.tag_raw);
        lit.push(b'"');
        let s = crate::convert::from_json_string(&lit).ok_or(Error::TypeMismatch {
            expected: "string tag",
            found: "invalid escape",
        })?;
        Ok(Cow::Owned(s))
    }
}

/// Decode an externally tagged **object** enum via tag → payload decoder.
///
/// The callback receives the decoded tag name and the raw payload JSON span.
/// On the hot path (unescaped ASCII tags) the name is borrowed from `json`.
#[inline]
pub fn read_external_object<T, F>(json: &[u8], mut decode: F) -> Result<T, Error>
where
    F: FnMut(&str, &[u8]) -> Result<T, Error>,
{
    let tag = peek_external_object(json)?;
    let name = tag.tag_cow()?;
    decode(name.as_ref(), tag.payload)
}

/// Decode an external enum that may be either a **unit string** or a **tagged object**.
///
/// Dispatches on the first non-whitespace byte (`"` vs `{`). Used by derive for
/// mixed enums (`None` | `Value(u64)`).
#[inline]
pub fn read_external<T, FU, FO>(
    json: &[u8],
    on_unit: FU,
    on_object: FO,
) -> Result<T, Error>
where
    FU: FnMut(&str) -> Option<T>,
    FO: FnMut(&str, &[u8]) -> Result<T, Error>,
{
    let start = skip_whitespace(json, 0);
    if start >= json.len() {
        return Err(Error::TypeMismatch {
            expected: "string or object (external enum)",
            found: "eof",
        });
    }
    match json[start] {
        b'"' => read_external_unit(json, on_unit),
        b'{' => read_external_object(json, on_object),
        _ => Err(Error::TypeMismatch {
            expected: "string or object (external enum)",
            found: type_hint(json, start),
        }),
    }
}

/// Emit an externally tagged unit: `"VariantName"`.
#[inline]
pub fn write_external_unit(out: &mut Vec<u8>, variant: &str) {
    crate::convert::write_json_string(out, variant);
}

/// Emit an externally tagged payload: `{"VariantName":<payload_json>}`.
///
/// `payload_json` must already be valid JSON text for the value (caller-built).
#[inline]
pub fn write_external_object(out: &mut Vec<u8>, variant: &str, payload_json: &[u8]) {
    // '{' + quotes + key + ':' + payload + '}'
    out.reserve(variant.len().saturating_add(payload_json.len()).saturating_add(8));
    out.push(b'{');
    crate::convert::write_json_string(out, variant);
    out.push(b':');
    out.extend_from_slice(payload_json);
    out.push(b'}');
}

/// Decode a struct-variant payload as `V: JsonView`.
#[inline]
pub fn payload_as_view<V: JsonView>(payload: &[u8]) -> Result<V, Error> {
    V::read_from(payload)
}

/// True when `json` (after leading ws) is a JSON string — unit external tag shape.
#[inline]
pub fn is_external_unit_shape(json: &[u8]) -> bool {
    let p = skip_whitespace(json, 0);
    p < json.len() && json[p] == b'"'
}

/// True when `json` (after leading ws) is a JSON object — object external tag shape.
#[inline]
pub fn is_external_object_shape(json: &[u8]) -> bool {
    let p = skip_whitespace(json, 0);
    p < json.len() && json[p] == b'{'
}

// ─── Internally tagged ───────────────────────────────────────────────────────

/// Read the string value of `tag_key` from a JSON **object** (internal/adjacent).
///
/// Returns a borrowed name when the on-wire string is unescaped.
#[inline]
pub fn read_tag_field<'a>(json: &'a [u8], tag_key: &str) -> Result<Cow<'a, str>, Error> {
    ensure_object_root(json)?;
    let path = [PathSegment::Key(tag_key)];
    let slice = find_value(json, &path).map_err(|e| match e {
        Error::PathNotFound => Error::Decode {
            path: tag_key.to_string(),
            expected: "tag field present",
            found: "missing tag key",
            pos: None,
        },
        other => other,
    })?;
    decode_json_string_cow(slice)
}

/// Decode an **internally tagged** enum.
///
/// Wire: `{"type":"Click","x":1,"y":2}` — the whole object is passed to
/// `decode` after the tag name is extracted (struct fields live beside `type`).
///
/// Unit variants typically only need the tag (`{"type":"Ready"}`).
///
/// `decode(name, object_json)` should use [`find_value`] on `object_json` for
/// fields. Unknown tags should return [`Error::Decode`].
#[inline]
pub fn read_internal<T, F>(json: &[u8], tag_key: &str, mut decode: F) -> Result<T, Error>
where
    F: FnMut(&str, &[u8]) -> Result<T, Error>,
{
    let name = read_tag_field(json, tag_key)?;
    // Whole document is the field bag (including the tag member).
    let start = skip_whitespace(json, 0);
    let end = skip_value(json, start)?;
    ensure_only_trailing_ws(json, end)?;
    decode(name.as_ref(), &json[start..end])
}

/// Emit an internally tagged **unit**: `{"type":"Ready"}`.
#[inline]
pub fn write_internal_unit(out: &mut Vec<u8>, tag_key: &str, variant: &str) {
    out.reserve(tag_key.len() + variant.len() + 16);
    out.push(b'{');
    crate::convert::write_json_string(out, tag_key);
    out.push(b':');
    crate::convert::write_json_string(out, variant);
    out.push(b'}');
}

/// Emit an internally tagged **struct**: tag field plus members from `fields_object`.
///
/// `fields_object` must be a JSON object (`{…}`) of the non-tag fields only.
/// Result: `{"type":"Click","x":1,"y":2}` (tag written first).
#[inline]
pub fn write_internal_fields(
    out: &mut Vec<u8>,
    tag_key: &str,
    variant: &str,
    fields_object: &[u8],
) {
    let fo = trim_ws(fields_object);
    assert_object_bytes(fo);
    out.reserve(tag_key.len() + variant.len() + fo.len() + 16);
    out.push(b'{');
    crate::convert::write_json_string(out, tag_key);
    out.push(b':');
    crate::convert::write_json_string(out, variant);
    // Strip `{` `}` from fields and splice remaining members.
    let inner = object_inner(fo);
    if !inner.is_empty() {
        out.push(b',');
        out.extend_from_slice(inner);
    }
    out.push(b'}');
}

// ─── Adjacently tagged ───────────────────────────────────────────────────────

/// Decode an **adjacently tagged** enum: `{"t":"Click","c":{…}}`.
///
/// * Unit variants: tag present, content key **absent** (or JSON `null`).
/// * Newtype / struct: content key holds the payload JSON span.
///
/// `decode(name, content)` receives `content = None` for pure units.
#[inline]
pub fn read_adjacent<T, F>(
    json: &[u8],
    tag_key: &str,
    content_key: &str,
    mut decode: F,
) -> Result<T, Error>
where
    F: FnMut(&str, Option<&[u8]>) -> Result<T, Error>,
{
    ensure_object_root(json)?;
    let name = read_tag_field(json, tag_key)?;
    let cpath = [PathSegment::Key(content_key)];
    let content = match find_value(json, &cpath) {
        Ok(slice) => {
            let t = trim_ws(slice);
            if t == b"null" {
                None
            } else {
                Some(slice)
            }
        }
        Err(Error::PathNotFound) => None,
        Err(e) => return Err(e),
    };
    let start = skip_whitespace(json, 0);
    let end = skip_value(json, start)?;
    ensure_only_trailing_ws(json, end)?;
    decode(name.as_ref(), content)
}

/// Emit adjacent unit: `{"t":"Ready"}` (no content key).
#[inline]
pub fn write_adjacent_unit(out: &mut Vec<u8>, tag_key: &str, variant: &str) {
    write_internal_unit(out, tag_key, variant);
}

/// Emit adjacent with content: `{"t":"Click","c":<payload>}`.
#[inline]
pub fn write_adjacent_content(
    out: &mut Vec<u8>,
    tag_key: &str,
    variant: &str,
    content_key: &str,
    payload_json: &[u8],
) {
    out.reserve(tag_key.len() + content_key.len() + variant.len() + payload_json.len() + 24);
    out.push(b'{');
    crate::convert::write_json_string(out, tag_key);
    out.push(b':');
    crate::convert::write_json_string(out, variant);
    out.push(b',');
    crate::convert::write_json_string(out, content_key);
    out.push(b':');
    out.extend_from_slice(payload_json);
    out.push(b'}');
}

// ─── Untagged ────────────────────────────────────────────────────────────────

/// Decode an **untagged** enum by trying `decoders` in order until one returns `Ok`.
///
/// Each decoder should return [`Error::Decode`] (or type mismatch) when the
/// shape does not match its variant so the next candidate can run. The last
/// error is returned if all fail.
///
/// ```
/// use jshift::{read_untagged, FromJsonSlice, Error};
///
/// #[derive(Debug, PartialEq)]
/// enum Val { N(u64), S(String) }
///
/// fn as_n(j: &[u8]) -> Result<Val, Error> {
///     Ok(Val::N(u64::from_json_slice(j).ok_or(Error::PathNotFound)?))
/// }
/// fn as_s(j: &[u8]) -> Result<Val, Error> {
///     Ok(Val::S(String::from_json_slice(j).ok_or(Error::PathNotFound)?))
/// }
///
/// let v = read_untagged(br#"42"#, [as_n, as_s]).unwrap();
/// assert_eq!(v, Val::N(42));
/// ```
pub fn read_untagged<T, I, F>(json: &[u8], decoders: I) -> Result<T, Error>
where
    I: IntoIterator<Item = F>,
    F: FnOnce(&[u8]) -> Result<T, Error>,
{
    let mut last = Error::Decode {
        path: String::new(),
        expected: "matching untagged variant",
        found: "no decoder succeeded",
        pos: None,
    };
    let mut any = false;
    for dec in decoders {
        any = true;
        match dec(json) {
            Ok(v) => return Ok(v),
            Err(e) => last = e,
        }
    }
    if !any {
        return Err(Error::Decode {
            path: String::new(),
            expected: "at least one untagged decoder",
            found: "empty decoder list",
            pos: None,
        });
    }
    Err(last)
}

// ─── Shared helpers ──────────────────────────────────────────────────────────

#[inline]
fn ensure_object_root(json: &[u8]) -> Result<(), Error> {
    let p = skip_whitespace(json, 0);
    if p >= json.len() || json[p] != b'{' {
        return Err(Error::TypeMismatch {
            expected: "object (tagged enum)",
            found: type_hint(json, p),
        });
    }
    Ok(())
}

#[inline]
fn trim_ws(json: &[u8]) -> &[u8] {
    let mut s = 0;
    let mut e = json.len();
    while s < e && matches!(json[s], b' ' | b'\t' | b'\n' | b'\r') {
        s += 1;
    }
    while e > s && matches!(json[e - 1], b' ' | b'\t' | b'\n' | b'\r') {
        e -= 1;
    }
    &json[s..e]
}

#[inline]
fn assert_object_bytes(fo: &[u8]) {
    debug_assert!(fo.first() == Some(&b'{') && fo.last() == Some(&b'}'));
}

#[inline]
fn object_inner(fo: &[u8]) -> &[u8] {
    let fo = trim_ws(fo);
    if fo.len() >= 2 && fo[0] == b'{' && fo[fo.len() - 1] == b'}' {
        trim_ws(&fo[1..fo.len() - 1])
    } else {
        fo
    }
}

fn decode_json_string_cow<'a>(slice: &'a [u8]) -> Result<Cow<'a, str>, Error> {
    let t = trim_ws(slice);
    if t.len() < 2 || t[0] != b'"' || t[t.len() - 1] != b'"' {
        return Err(Error::TypeMismatch {
            expected: "string (enum tag)",
            found: type_hint(t, 0),
        });
    }
    let raw = &t[1..t.len() - 1];
    if !raw.contains(&b'\\') {
        let s = std::str::from_utf8(raw).map_err(|_| Error::TypeMismatch {
            expected: "utf-8 tag",
            found: "invalid utf-8",
        })?;
        return Ok(Cow::Borrowed(s));
    }
    let s = crate::convert::from_json_string(t).ok_or(Error::TypeMismatch {
        expected: "string tag",
        found: "invalid escape",
    })?;
    Ok(Cow::Owned(s))
}

#[inline]
fn ensure_only_trailing_ws(json: &[u8], pos: usize) -> Result<(), Error> {
    let pos = skip_whitespace(json, pos);
    if pos < json.len() {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Trailing data after enum value",
        });
    }
    Ok(())
}

#[inline]
fn type_hint(json: &[u8], pos: usize) -> &'static str {
    if pos >= json.len() {
        return "eof";
    }
    match json[pos] {
        b'{' => "object",
        b'[' => "array",
        b'"' => "string",
        b't' | b'f' => "bool",
        b'n' => "null",
        b'-' | b'0'..=b'9' => "number",
        _ => "invalid",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{find_value, parse_path, FromJsonSlice, ToJsonBytes};

    #[test]
    fn unit_and_object_tags() {
        let u = read_external_unit(br#""Ready""#, |s| match s {
            "Ready" => Some(1u8),
            "Done" => Some(2),
            _ => None,
        })
        .unwrap();
        assert_eq!(u, 1);

        let tag = peek_external_object(br#"{"Click":{"x":1,"y":2}}"#).unwrap();
        assert_eq!(tag.tag_str().unwrap(), "Click");
        assert_eq!(
            u64::from_json_slice(find_value(tag.payload, &parse_path("x")).unwrap()).unwrap(),
            1
        );

        let mut out = Vec::new();
        write_external_object(&mut out, "Id", &7u64.to_json_bytes());
        assert_eq!(out, br#"{"Id":7}"#);
    }

    #[test]
    fn unit_zero_copy_and_ws() {
        let json = br#"  "Ready"  "#;
        // name must be a subslice of input when unescaped
        let name_ptr = read_external_unit(json, |s| {
            assert_eq!(s, "Ready");
            // pointer into `json`
            Some(s.as_ptr() as usize)
        })
        .unwrap();
        assert!(name_ptr >= json.as_ptr() as usize);
        assert!(name_ptr < json.as_ptr() as usize + json.len());
    }

    #[test]
    fn rejects_trailing_junk() {
        assert!(read_external_unit(br#""Ready"0"#, |_| Some(1u8)).is_err());
        assert!(peek_external_object(br#"{"A":1}0"#).is_err());
    }

    #[test]
    fn rejects_multi_key_and_empty() {
        assert!(peek_external_object(br#"{"A":1,"B":2}"#).is_err());
        assert!(peek_external_object(br#"{}"#).is_err());
    }

    #[test]
    fn object_tag_zero_alloc_unescaped() {
        let json = br#"{"Click":{"x":1}}"#;
        read_external_object(json, |name, payload| {
            assert_eq!(name, "Click");
            // unescaped path borrows from input
            assert_eq!(
                name.as_ptr() as usize,
                json.as_ptr() as usize + 2 // after `{"`
            );
            assert!(payload.starts_with(b"{"));
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn mixed_read_external() {
        #[derive(Debug, PartialEq)]
        enum E {
            None,
            Id(u64),
        }
        let n = read_external(
            br#""None""#,
            |s| match s {
                "None" => Some(E::None),
                _ => None,
            },
            |name, payload| match name {
                "Id" => Ok(E::Id(u64::from_json_slice(payload).unwrap())),
                _ => Err(Error::PathNotFound),
            },
        )
        .unwrap();
        assert_eq!(n, E::None);

        let i = read_external(
            br#"{"Id":9}"#,
            |_| None,
            |name, payload| match name {
                "Id" => Ok(E::Id(u64::from_json_slice(payload).unwrap())),
                _ => Err(Error::PathNotFound),
            },
        )
        .unwrap();
        assert_eq!(i, E::Id(9));
    }

    #[test]
    fn escaped_unit_tag() {
        let v = read_external_unit(br#""say \"hi\"""#, |s| {
            if s == "say \"hi\"" {
                Some(1u8)
            } else {
                None
            }
        })
        .unwrap();
        assert_eq!(v, 1);
    }

    #[test]
    fn internal_unit_and_struct() {
        #[derive(Debug, PartialEq)]
        enum Ev {
            Ready,
            Click { x: u64, y: u64 },
        }
        let u = read_internal(br#"{"type":"Ready"}"#, "type", |name, _| match name {
            "Ready" => Ok(Ev::Ready),
            _ => Err(Error::PathNotFound),
        })
        .unwrap();
        assert_eq!(u, Ev::Ready);

        let c = read_internal(
            br#"{"type":"Click","x":3,"y":4}"#,
            "type",
            |name, obj| match name {
                "Click" => Ok(Ev::Click {
                    x: u64::from_json_slice(find_value(obj, &parse_path("x")).unwrap()).unwrap(),
                    y: u64::from_json_slice(find_value(obj, &parse_path("y")).unwrap()).unwrap(),
                }),
                _ => Err(Error::PathNotFound),
            },
        )
        .unwrap();
        assert_eq!(c, Ev::Click { x: 3, y: 4 });

        let mut out = Vec::new();
        write_internal_unit(&mut out, "type", "Ready");
        assert_eq!(out, br#"{"type":"Ready"}"#);

        let mut out = Vec::new();
        write_internal_fields(&mut out, "type", "Click", br#"{"x":3,"y":4}"#);
        assert_eq!(out, br#"{"type":"Click","x":3,"y":4}"#);
    }

    #[test]
    fn adjacent_unit_and_content() {
        #[derive(Debug, PartialEq)]
        enum Ev {
            Ready,
            Id(u64),
        }
        let u = read_adjacent(br#"{"t":"Ready"}"#, "t", "c", |name, c| match (name, c) {
            ("Ready", None) => Ok(Ev::Ready),
            _ => Err(Error::PathNotFound),
        })
        .unwrap();
        assert_eq!(u, Ev::Ready);

        let i = read_adjacent(br#"{"t":"Id","c":9}"#, "t", "c", |name, c| match (name, c) {
            ("Id", Some(p)) => Ok(Ev::Id(u64::from_json_slice(p).unwrap())),
            _ => Err(Error::PathNotFound),
        })
        .unwrap();
        assert_eq!(i, Ev::Id(9));

        let mut out = Vec::new();
        write_adjacent_content(&mut out, "t", "Id", "c", b"9");
        assert_eq!(out, br#"{"t":"Id","c":9}"#);
    }

    #[test]
    fn untagged_number_then_string() {
        #[derive(Debug, PartialEq)]
        enum Val {
            N(u64),
            S(String),
        }
        let n = read_untagged(
            br#"42"#,
            [
                |j: &[u8]| {
                    Ok(Val::N(
                        u64::from_json_slice(j).ok_or(Error::PathNotFound)?,
                    ))
                },
                |j: &[u8]| {
                    Ok(Val::S(
                        String::from_json_slice(j).ok_or(Error::PathNotFound)?,
                    ))
                },
            ],
        )
        .unwrap();
        assert_eq!(n, Val::N(42));

        let s = read_untagged(
            br#""hi""#,
            [
                |j: &[u8]| {
                    Ok(Val::N(
                        u64::from_json_slice(j).ok_or(Error::PathNotFound)?,
                    ))
                },
                |j: &[u8]| {
                    Ok(Val::S(
                        String::from_json_slice(j).ok_or(Error::PathNotFound)?,
                    ))
                },
            ],
        )
        .unwrap();
        assert_eq!(s, Val::S("hi".into()));
    }
}