forma_json 0.1.0

JSON serialization and deserialization for forma_core.
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
use crate::error::Error;
use forma_core::de::*;

/// Default maximum nesting depth. Prevents stack overflow on malicious input.
const DEFAULT_DEPTH_LIMIT: usize = 128;

pub struct Deserializer<'de> {
    input: &'de [u8],
    pos: usize,
    line: usize,
    col: usize,
    remaining_depth: usize,
    lenient: bool,
}

impl<'de> Deserializer<'de> {
    pub fn new(input: &'de [u8]) -> Self {
        Deserializer {
            input,
            pos: 0,
            line: 1,
            col: 1,
            remaining_depth: DEFAULT_DEPTH_LIMIT,
            lenient: false,
        }
    }

    /// Set a custom recursion depth limit.
    pub fn set_depth_limit(&mut self, limit: usize) {
        self.remaining_depth = limit;
    }

    /// Enable lenient mode: coerce compatible types instead of erroring.
    /// Accepts strings as numbers/bools, single values as arrays, etc.
    pub fn set_lenient(&mut self, lenient: bool) {
        self.lenient = lenient;
    }

    pub fn from_str(input: &'de str) -> Self {
        Self::new(input.as_bytes())
    }

    #[inline]
    fn peek(&self) -> Option<u8> {
        self.input.get(self.pos).copied()
    }

    #[inline]
    fn advance(&mut self) -> Option<u8> {
        let b = self.input.get(self.pos).copied()?;
        self.pos += 1;
        if b == b'\n' {
            self.line += 1;
            self.col = 1;
        } else {
            self.col += 1;
        }
        Some(b)
    }

    #[inline]
    fn skip_whitespace(&mut self) {
        // Bulk scan: skip over ASCII whitespace bytes directly in the slice,
        // only updating line/col when we actually find newlines.
        let bytes = &self.input[self.pos..];
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b' ' | b'\t' | b'\r' => {
                    i += 1;
                    self.col += 1;
                }
                b'\n' => {
                    i += 1;
                    self.line += 1;
                    self.col = 1;
                }
                _ => break,
            }
        }
        self.pos += i;
    }

    fn peek_or_eof(&mut self) -> Result<u8, Error> {
        self.skip_whitespace();
        self.peek().ok_or(Error::Eof)
    }

    fn next_or_eof(&mut self) -> Result<u8, Error> {
        self.advance().ok_or(Error::Eof)
    }

    fn expect(&mut self, expected: u8) -> Result<(), Error> {
        self.skip_whitespace();
        match self.advance() {
            Some(b) if b == expected => Ok(()),
            Some(_) => Err(Error::Syntax(
                format!("expected '{}'", expected as char),
                self.line,
                self.col - 1,
            )),
            None => Err(Error::Eof),
        }
    }

    /// Parse a JSON string. Uses a fast path that scans for the closing quote
    /// without escapes — if the entire string is plain ASCII with no backslashes,
    /// we copy it in one shot. Falls back to byte-by-byte only when escapes or
    /// multi-byte UTF-8 are present.
    fn parse_string(&mut self) -> Result<String, Error> {
        self.skip_whitespace();
        self.expect(b'"')?;

        // Fast path: scan for closing quote with no escapes and no high bytes.
        let start = self.pos;
        let bytes = &self.input[start..];
        let mut i = 0;
        loop {
            if i >= bytes.len() {
                // Ran off the end — fall through to slow path for proper error.
                break;
            }
            match bytes[i] {
                b'"' => {
                    // All clean — copy the slice and advance past the closing quote.
                    // SAFETY: we only get here if every byte was < 0x80 and not a
                    // backslash, so the slice is valid ASCII (and thus UTF-8).
                    let s = unsafe { std::str::from_utf8_unchecked(&bytes[..i]) }.to_owned();
                    self.pos = start + i + 1;
                    self.col += i + 1; // i chars + closing quote
                    return Ok(s);
                }
                b'\\' | 0x80..=0xFF => {
                    // Escape or multi-byte UTF-8 — need slow path.
                    // But we can still keep the clean prefix we already scanned.
                    break;
                }
                b'\n' => {
                    // Raw newline inside a string is invalid JSON, but let the
                    // slow path handle the error reporting with proper line/col.
                    break;
                }
                _ => {
                    i += 1;
                }
            }
        }

        // Slow path: we may have a clean prefix [start..start+i], then escapes
        // or multi-byte follow. Start the string from the clean prefix.
        let mut s = String::from(
            // SAFETY: same reasoning — all scanned bytes are ASCII.
            unsafe { std::str::from_utf8_unchecked(&self.input[start..start + i]) },
        );
        self.pos = start + i;
        self.col += i;

        loop {
            match self.next_or_eof()? {
                b'"' => return Ok(s),
                b'\\' => {
                    match self.next_or_eof()? {
                        b'"' => s.push('"'),
                        b'\\' => s.push('\\'),
                        b'/' => s.push('/'),
                        b'n' => s.push('\n'),
                        b'r' => s.push('\r'),
                        b't' => s.push('\t'),
                        b'b' => s.push('\u{0008}'),
                        b'f' => s.push('\u{000C}'),
                        b'u' => {
                            let cp = self.parse_hex4()?;
                            if (0xD800..=0xDBFF).contains(&cp) {
                                // High surrogate — expect \uXXXX low surrogate
                                self.expect(b'\\')?;
                                self.expect(b'u')?;
                                let low = self.parse_hex4()?;
                                if !(0xDC00..=0xDFFF).contains(&low) {
                                    return Err(Error::Syntax(
                                        "invalid surrogate pair".into(),
                                        self.line,
                                        self.col,
                                    ));
                                }
                                let cp = 0x10000
                                    + ((cp as u32 - 0xD800) << 10)
                                    + (low as u32 - 0xDC00);
                                s.push(char::from_u32(cp).ok_or_else(|| {
                                    Error::Syntax(
                                        "invalid unicode codepoint".into(),
                                        self.line,
                                        self.col,
                                    )
                                })?);
                            } else {
                                s.push(char::from_u32(cp as u32).ok_or_else(|| {
                                    Error::Syntax(
                                        "invalid unicode codepoint".into(),
                                        self.line,
                                        self.col,
                                    )
                                })?);
                            }
                        }
                        _ => {
                            return Err(Error::Syntax(
                                "invalid escape".into(),
                                self.line,
                                self.col,
                            ))
                        }
                    }
                }
                b if b < 0x80 => s.push(b as char),
                b => {
                    // Multi-byte UTF-8: determine sequence length and decode.
                    let len = if b & 0xE0 == 0xC0 {
                        2
                    } else if b & 0xF0 == 0xE0 {
                        3
                    } else if b & 0xF8 == 0xF0 {
                        4
                    } else {
                        return Err(Error::Syntax(
                            "invalid UTF-8 byte".into(),
                            self.line,
                            self.col,
                        ));
                    };
                    let start = self.pos - 1; // already advanced past `b`
                    for _ in 1..len {
                        match self.advance() {
                            Some(cont) if cont & 0xC0 == 0x80 => {}
                            _ => {
                                return Err(Error::Syntax(
                                    "invalid UTF-8 continuation byte".into(),
                                    self.line,
                                    self.col,
                                ));
                            }
                        }
                    }
                    let utf8_bytes = &self.input[start..self.pos];
                    match std::str::from_utf8(utf8_bytes) {
                        Ok(ch) => s.push_str(ch),
                        Err(_) => {
                            return Err(Error::Syntax(
                                "invalid UTF-8 sequence".into(),
                                self.line,
                                self.col,
                            ));
                        }
                    }
                }
            }
        }
    }

    fn parse_hex4(&mut self) -> Result<u16, Error> {
        let mut val = 0u16;
        for _ in 0..4 {
            let b = self.next_or_eof()?;
            let digit = match b {
                b'0'..=b'9' => b - b'0',
                b'a'..=b'f' => b - b'a' + 10,
                b'A'..=b'F' => b - b'A' + 10,
                _ => {
                    return Err(Error::Syntax(
                        "invalid hex digit".into(),
                        self.line,
                        self.col,
                    ))
                }
            };
            val = (val << 4) | digit as u16;
        }
        Ok(val)
    }

    /// Parse number bytes by bulk-scanning for digits and number chars.
    /// Per RFC 8259, leading `+` is not valid JSON. The `+` sign is only
    /// permitted immediately after an exponent indicator (`e` or `E`).
    #[inline]
    fn parse_number_bytes(&mut self) -> &'de [u8] {
        let start = self.pos;
        let bytes = &self.input[start..];
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'0'..=b'9' | b'-' | b'.' | b'e' | b'E' => i += 1,
                b'+' => {
                    // Only allow '+' immediately after 'e' or 'E'
                    if i > 0 && matches!(bytes[i - 1], b'e' | b'E') {
                        i += 1;
                    } else {
                        break;
                    }
                }
                _ => break,
            }
        }
        self.col += i;
        self.pos = start + i;
        &self.input[start..self.pos]
    }

    #[inline]
    fn check_depth(&mut self) -> Result<(), Error> {
        if self.remaining_depth == 0 {
            return Err(Error::Message("recursion limit exceeded".into()));
        }
        self.remaining_depth -= 1;
        Ok(())
    }

    #[inline]
    fn restore_depth(&mut self) {
        self.remaining_depth += 1;
    }

    pub fn end_of_input(&mut self) -> Result<(), Error> {
        self.skip_whitespace();
        if self.pos < self.input.len() {
            Err(Error::TrailingData)
        } else {
            Ok(())
        }
    }
}

impl<'de, 'a> forma_core::de::Deserializer<'de> for &'a mut Deserializer<'de> {
    type Error = Error;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        match self.peek_or_eof()? {
            b'"' => {
                let s = self.parse_string()?;
                visitor.visit_string(s)
            }
            b't' | b'f' => self.deserialize_bool(visitor),
            b'n' => {
                self.skip_whitespace();
                self.expect(b'n')?;
                self.expect(b'u')?;
                self.expect(b'l')?;
                self.expect(b'l')?;
                visitor.visit_unit()
            }
            b'[' => self.deserialize_seq(visitor),
            b'{' => self.deserialize_map(visitor),
            b'0'..=b'9' | b'-' => {
                self.skip_whitespace();
                let num_bytes = self.parse_number_bytes();
                let num_str = std::str::from_utf8(num_bytes).map_err(|_| {
                    Error::Syntax("invalid number".into(), self.line, self.col)
                })?;
                if num_str.contains('.') || num_str.contains('e') || num_str.contains('E') {
                    let v: f64 = num_str.parse().map_err(|_| {
                        Error::Syntax(format!("invalid number: {num_str}"), self.line, self.col)
                    })?;
                    visitor.visit_f64(v)
                } else if num_str.starts_with('-') {
                    let v: i64 = num_str.parse().map_err(|_| {
                        Error::Syntax(format!("invalid number: {num_str}"), self.line, self.col)
                    })?;
                    visitor.visit_i64(v)
                } else {
                    let v: u64 = num_str.parse().map_err(|_| {
                        Error::Syntax(format!("invalid number: {num_str}"), self.line, self.col)
                    })?;
                    visitor.visit_u64(v)
                }
            }
            b => Err(Error::Syntax(
                format!("unexpected character '{}'", b as char),
                self.line,
                self.col,
            )),
        }
    }

    fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        if self.lenient {
            match self.peek_or_eof()? {
                b'"' => {
                    let s = self.parse_string()?;
                    return match s.as_str() {
                        "true" | "1" => visitor.visit_bool(true),
                        "false" | "0" => visitor.visit_bool(false),
                        _ => Err(Error::Syntax(
                            format!("cannot coerce \"{}\" to bool", s),
                            self.line, self.col,
                        )),
                    };
                }
                b'0' | b'1' => {
                    let bytes = self.parse_number_bytes();
                    return match bytes {
                        [b'0'] => visitor.visit_bool(false),
                        [b'1'] => visitor.visit_bool(true),
                        _ => Err(Error::Syntax(
                            "cannot coerce number to bool".into(),
                            self.line, self.col,
                        )),
                    };
                }
                _ => {}
            }
        }
        match self.peek_or_eof()? {
            b't' => {
                self.advance(); // t
                self.expect(b'r')?;
                self.expect(b'u')?;
                self.expect(b'e')?;
                visitor.visit_bool(true)
            }
            b'f' => {
                self.advance(); // f
                self.expect(b'a')?;
                self.expect(b'l')?;
                self.expect(b's')?;
                self.expect(b'e')?;
                visitor.visit_bool(false)
            }
            _ => Err(Error::Syntax(
                "expected bool".into(),
                self.line,
                self.col,
            )),
        }
    }

    fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_i64(visitor)
    }
    fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_i64(visitor)
    }
    fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_i64(visitor)
    }
    fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        if self.lenient && self.peek() == Some(b'"') {
            let s = self.parse_string()?;
            let v: i64 = s.parse().map_err(|_| {
                Error::Syntax(format!("cannot coerce \"{}\" to i64", s), self.line, self.col)
            })?;
            return visitor.visit_i64(v);
        }
        let bytes = self.parse_number_bytes();
        let s = std::str::from_utf8(bytes)
            .map_err(|_| Error::Syntax("invalid number".into(), self.line, self.col))?;
        let v: i64 = s
            .parse()
            .map_err(|_| Error::Syntax(format!("invalid i64: {s}"), self.line, self.col))?;
        visitor.visit_i64(v)
    }
    fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        let bytes = self.parse_number_bytes();
        let s = std::str::from_utf8(bytes)
            .map_err(|_| Error::Syntax("invalid number".into(), self.line, self.col))?;
        let v: i128 = s
            .parse()
            .map_err(|_| Error::Syntax(format!("invalid i128: {s}"), self.line, self.col))?;
        visitor.visit_i128(v)
    }

    fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_u64(visitor)
    }
    fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_u64(visitor)
    }
    fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_u64(visitor)
    }
    fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        if self.lenient && self.peek() == Some(b'"') {
            let s = self.parse_string()?;
            let v: u64 = s.parse().map_err(|_| {
                Error::Syntax(format!("cannot coerce \"{}\" to u64", s), self.line, self.col)
            })?;
            return visitor.visit_u64(v);
        }
        let bytes = self.parse_number_bytes();
        let s = std::str::from_utf8(bytes)
            .map_err(|_| Error::Syntax("invalid number".into(), self.line, self.col))?;
        let v: u64 = s
            .parse()
            .map_err(|_| Error::Syntax(format!("invalid u64: {s}"), self.line, self.col))?;
        visitor.visit_u64(v)
    }
    fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        let bytes = self.parse_number_bytes();
        let s = std::str::from_utf8(bytes)
            .map_err(|_| Error::Syntax("invalid number".into(), self.line, self.col))?;
        let v: u128 = s
            .parse()
            .map_err(|_| Error::Syntax(format!("invalid u128: {s}"), self.line, self.col))?;
        visitor.visit_u128(v)
    }

    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_f64(visitor)
    }
    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        if self.lenient && self.peek() == Some(b'"') {
            let s = self.parse_string()?;
            let v: f64 = s.parse().map_err(|_| {
                Error::Syntax(format!("cannot coerce \"{}\" to f64", s), self.line, self.col)
            })?;
            return visitor.visit_f64(v);
        }
        let bytes = self.parse_number_bytes();
        let s = std::str::from_utf8(bytes)
            .map_err(|_| Error::Syntax("invalid number".into(), self.line, self.col))?;
        let v: f64 = s
            .parse()
            .map_err(|_| Error::Syntax(format!("invalid f64: {s}"), self.line, self.col))?;
        visitor.visit_f64(v)
    }

    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        let s = self.parse_string()?;
        let mut chars = s.chars();
        match (chars.next(), chars.next()) {
            (Some(c), None) => visitor.visit_char(c),
            _ => Err(Error::Syntax(
                "expected single character".into(),
                self.line,
                self.col,
            )),
        }
    }

    fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        let s = self.parse_string()?;
        visitor.visit_string(s)
    }

    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_str(visitor)
    }

    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_bytes(visitor)
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        if self.peek() == Some(b'n') {
            self.advance(); // n
            self.expect(b'u')?;
            self.expect(b'l')?;
            self.expect(b'l')?;
            visitor.visit_none()
        } else {
            visitor.visit_some(self)
        }
    }

    fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.skip_whitespace();
        self.expect(b'n')?;
        self.expect(b'u')?;
        self.expect(b'l')?;
        self.expect(b'l')?;
        visitor.visit_unit()
    }

    fn deserialize_unit_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Error> {
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Error> {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.check_depth()?;
        self.skip_whitespace();
        // Lenient: wrap a single non-array value into a one-element sequence.
        if self.lenient && self.peek() != Some(b'[') {
            let value = visitor.visit_seq(SingleElementSeq { de: self, done: false })?;
            self.restore_depth();
            return Ok(value);
        }
        self.expect(b'[')?;
        let value = visitor.visit_seq(SeqAccess::new(self))?;
        self.expect(b']')?;
        self.restore_depth();
        Ok(value)
    }

    fn deserialize_tuple<V: Visitor<'de>>(
        self,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Error> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Error> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.check_depth()?;
        self.skip_whitespace();
        self.expect(b'{')?;
        let value = visitor.visit_map(MapAccess::new(self))?;
        self.expect(b'}')?;
        self.restore_depth();
        Ok(value)
    }

    fn deserialize_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error> {
        self.deserialize_map(visitor)
    }

    fn deserialize_enum<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error> {
        self.skip_whitespace();
        match self.peek_or_eof()? {
            // "variant" — string means unit variant
            b'"' => visitor.visit_enum(UnitVariantAccess::new(self)),
            // { "variant": content } — object means newtype/tuple/struct variant
            b'{' => {
                self.check_depth()?;
                self.advance(); // {
                let value = visitor.visit_enum(VariantMapAccess::new(self))?;
                self.skip_whitespace();
                self.expect(b'}')?;
                self.restore_depth();
                Ok(value)
            }
            _ => Err(Error::Syntax(
                "expected string or object for enum".into(),
                self.line,
                self.col,
            )),
        }
    }


    fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_str(visitor)
    }

    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
        self.deserialize_any(visitor)
    }
}

// ── SeqAccess ────────────────────────────────────────────────────────

struct SeqAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    first: bool,
}

impl<'a, 'de> SeqAccess<'a, 'de> {
    fn new(de: &'a mut Deserializer<'de>) -> Self {
        SeqAccess { de, first: true }
    }
}

impl<'de> forma_core::de::SeqAccess<'de> for SeqAccess<'_, 'de> {
    type Error = Error;

    fn next_element_seed<T: DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>, Error> {
        self.de.skip_whitespace();
        if self.de.peek() == Some(b']') {
            return Ok(None);
        }
        if !self.first {
            self.de.expect(b',')?;
        }
        self.first = false;
        seed.deserialize(&mut *self.de).map(Some)
    }
}

// ── MapAccess ────────────────────────────────────────────────────────

struct MapAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    first: bool,
}

impl<'a, 'de> MapAccess<'a, 'de> {
    fn new(de: &'a mut Deserializer<'de>) -> Self {
        MapAccess { de, first: true }
    }
}

impl<'de> forma_core::de::MapAccess<'de> for MapAccess<'_, 'de> {
    type Error = Error;

    fn next_key_seed<K: DeserializeSeed<'de>>(
        &mut self,
        seed: K,
    ) -> Result<Option<K::Value>, Error> {
        self.de.skip_whitespace();
        if self.de.peek() == Some(b'}') {
            return Ok(None);
        }
        if !self.first {
            self.de.expect(b',')?;
        }
        self.first = false;
        seed.deserialize(&mut *self.de).map(Some)
    }

    fn next_value_seed<V: DeserializeSeed<'de>>(
        &mut self,
        seed: V,
    ) -> Result<V::Value, Error> {
        self.de.expect(b':')?;
        seed.deserialize(&mut *self.de)
    }
}

// ── Enum variant access ──────────────────────────────────────────────

// String enum: "Red" → unit variant
struct UnitVariantAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
}

impl<'a, 'de> UnitVariantAccess<'a, 'de> {
    fn new(de: &'a mut Deserializer<'de>) -> Self {
        UnitVariantAccess { de }
    }
}

impl<'de> forma_core::de::EnumAccess<'de> for UnitVariantAccess<'_, 'de> {
    type Error = Error;
    type Variant = UnitOnly;

    fn variant_seed<V: DeserializeSeed<'de>>(
        self,
        seed: V,
    ) -> Result<(V::Value, UnitOnly), Error> {
        let variant = seed.deserialize(&mut *self.de)?;
        Ok((variant, UnitOnly))
    }
}

struct UnitOnly;

impl<'de> forma_core::de::VariantAccess<'de> for UnitOnly {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Error> {
        Ok(())
    }

    fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, _seed: T) -> Result<T::Value, Error> {
        Err(Error::Message(
            "expected unit variant, got newtype".into(),
        ))
    }

    fn tuple_variant<V: Visitor<'de>>(self, _len: usize, _visitor: V) -> Result<V::Value, Error> {
        Err(Error::Message("expected unit variant, got tuple".into()))
    }

    fn struct_variant<V: Visitor<'de>>(
        self,
        _fields: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value, Error> {
        Err(Error::Message(
            "expected unit variant, got struct".into(),
        ))
    }
}

// Object enum: {"Variant": content}
struct VariantMapAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
}

impl<'a, 'de> VariantMapAccess<'a, 'de> {
    fn new(de: &'a mut Deserializer<'de>) -> Self {
        VariantMapAccess { de }
    }
}

impl<'a, 'de> forma_core::de::EnumAccess<'de> for VariantMapAccess<'a, 'de> {
    type Error = Error;
    type Variant = VariantContentAccess<'a, 'de>;

    fn variant_seed<V: DeserializeSeed<'de>>(
        self,
        seed: V,
    ) -> Result<(V::Value, VariantContentAccess<'a, 'de>), Error> {
        let variant = seed.deserialize(&mut *self.de)?;
        self.de.expect(b':')?;
        Ok((variant, VariantContentAccess { de: self.de }))
    }
}

struct VariantContentAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
}

impl<'de> forma_core::de::VariantAccess<'de> for VariantContentAccess<'_, 'de> {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Error> {
        forma_core::de::Deserialize::deserialize(self.de)
    }

    fn newtype_variant_seed<T: DeserializeSeed<'de>>(
        self,
        seed: T,
    ) -> Result<T::Value, Error> {
        seed.deserialize(self.de)
    }

    fn tuple_variant<V: Visitor<'de>>(
        self,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Error> {
        forma_core::de::Deserializer::deserialize_seq(self.de, visitor)
    }

    fn struct_variant<V: Visitor<'de>>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error> {
        forma_core::de::Deserializer::deserialize_map(self.de, visitor)
    }
}

// ── Lenient helpers ──────────────────────────────────────────────────

/// A SeqAccess that yields exactly one element (for lenient single-to-array coercion).
struct SingleElementSeq<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    done: bool,
}

impl<'de> forma_core::de::SeqAccess<'de> for SingleElementSeq<'_, 'de> {
    type Error = Error;

    fn next_element_seed<T: DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>, Error> {
        if self.done {
            return Ok(None);
        }
        self.done = true;
        seed.deserialize(&mut *self.de).map(Some)
    }
}