nanojson 0.5.0

A #![no_std], allocation-free, zero-dependency JSON serializer and pull-parser.
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
use crate::{Write, WriteError};

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ScopeKind {
    Array,
    Object,
}

#[derive(Copy, Clone)]
struct Scope {
    kind: ScopeKind,
    /// At least one element has been written.
    tail: bool,
    /// An object key was just placed; next write is the value.
    key: bool,
}

/// JSON serializer. Generic over the write sink `W` and maximum nesting depth `DEPTH`.
///
/// # Example
/// ```
/// use nanojson::{Serializer, SliceWriter};
/// let mut buf = [0u8; 64];
/// let mut w = SliceWriter::new(&mut buf);
/// let mut ser: Serializer<_, 32> = Serializer::new(&mut w);
/// ser.object_begin().unwrap();
/// ser.member("x").unwrap(); ser.integer(1).unwrap();
/// ser.object_end().unwrap();
/// drop(ser);
/// assert_eq!(w.written(), b"{\"x\":1}");
/// ```
pub struct Serializer<W, const DEPTH: usize = 32> {
    writer: W,
    scopes: [Scope; DEPTH],
    depth: usize,
    /// Pretty-print indent width in spaces. `0` = compact output (default).
    ///
    /// Setting this to a very large value causes the serializer to write that many
    /// space bytes per nesting level. Reasonable values are `2` or `4`.
    pub pp: usize,
}

/// Error type for the serializer: either a write error from the sink, or nesting depth exceeded.
#[derive(Debug)]
pub enum SerializeError<E> {
    Write(E),
    DepthExceeded,
    /// `member` / `member_bytes` was called outside an object scope,
    /// or was called twice without an intervening value.
    InvalidState,
    /// The serializer generated invalid UTF-8 at some point.
    InvalidUtf8(usize),
    /// A value cannot be represented as JSON (e.g. a NaN or infinite float).
    InvalidValue(&'static str),
}

impl<E> From<E> for SerializeError<E> {
    fn from(e: E) -> Self {
        SerializeError::Write(e)
    }
}

impl<E: core::fmt::Display> core::fmt::Display for SerializeError<E> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Write(e)          => write!(f, "write error: {e}"),
            Self::DepthExceeded     => f.write_str("nesting depth exceeded"),
            Self::InvalidState      => f.write_str("invalid serializer call order"),
            Self::InvalidValue(m)   => write!(f, "invalid value: {m}"),
            Self::InvalidUtf8(off)  => write!(f, "invalid utf-8 generated at: {off}"),
        }
    }
}

#[cfg(feature = "std")]
impl<E: std::error::Error + 'static> std::error::Error for SerializeError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SerializeError::Write(e) => Some(e),
            _ => None,
        }
    }
}


// Serialize an unsigned integer to decimal without allocating.
// BUF_SIZE must be large enough for the type's maximum decimal digits (u64→20, u128→39).
macro_rules! write_uint_raw {
    ($self:expr, $x:expr, $t:ty, $buf_size:literal) => {{
        let x: $t = $x;
        if x == 0 { return $self.write(b"0"); }
        let mut buf = [0u8; $buf_size];
        let mut i = $buf_size;
        let mut n = x;
        while n > 0 { i -= 1; buf[i] = b'0' + (n % 10) as u8; n /= 10; }
        $self.write(&buf[i..])
    }};
}

impl<W: Write, const DEPTH: usize> Serializer<W, DEPTH> {
    pub fn new(writer: W) -> Self {
        Self {
            writer,
            scopes: [Scope { kind: ScopeKind::Array, tail: false, key: false }; DEPTH],
            depth: 0,
            pp: 0,
        }
    }

    pub fn with_pretty(writer: W, indent: usize) -> Self {
        let mut s = Self::new(writer);
        s.pp = indent;
        s
    }

    /// Consume the serializer and return the inner writer.
    pub fn into_writer(self) -> W {
        self.writer
    }

    // ---- internal helpers ----

    fn write(&mut self, b: &[u8]) -> Result<(), SerializeError<W::Error>> {
        self.writer.write_bytes(b).map_err(SerializeError::Write)
    }

    fn current_scope(&mut self) -> Option<&mut Scope> {
        if self.depth > 0 {
            Some(&mut self.scopes[self.depth - 1])
        } else {
            None
        }
    }

    fn element_begin(&mut self) -> Result<(), SerializeError<W::Error>> {
        // We need to read scope fields without holding a mutable borrow on self,
        // so copy out what we need.
        let (tail, key, depth) = if let Some(s) = self.current_scope() {
            (s.tail, s.key, self.depth)
        } else {
            return Ok(());
        };

        if tail && !key {
            self.write(b",")?;
        }

        if self.pp > 0 {
            if key {
                self.write(b" ")?;
            } else {
                self.write(b"\n")?;
                for _ in 0..depth * self.pp {
                    self.write(b" ")?;
                }
            }
        }
        Ok(())
    }

    fn element_end(&mut self) {
        if let Some(s) = self.current_scope() {
            s.tail = true;
            s.key = false;
        }
    }

    fn push_scope(&mut self, kind: ScopeKind) -> Result<(), SerializeError<W::Error>> {
        if self.depth >= DEPTH {
            return Err(SerializeError::DepthExceeded);
        }
        self.scopes[self.depth] = Scope { kind, tail: false, key: false };
        self.depth += 1;
        Ok(())
    }

    fn pop_scope(&mut self) {
        if self.depth > 0 {
            self.depth -= 1;
        }
    }

    fn write_closing(&mut self, close: &[u8]) -> Result<(), SerializeError<W::Error>> {
        let (tail, depth) = if let Some(s) = self.current_scope() {
            (s.tail, self.depth)
        } else {
            (false, 0)
        };
        if self.pp > 0 && tail {
            self.write(b"\n")?;
            for _ in 0..(depth.saturating_sub(1)) * self.pp {
                self.write(b" ")?;
            }
        }
        self.write(close)
    }

    fn write_integer_raw(&mut self, x: i64) -> Result<(), SerializeError<W::Error>> {
        if x < 0 { self.write(b"-")?; }
        self.write_u64_raw(x.unsigned_abs())
    }

    fn write_u64_raw(&mut self, x: u64) -> Result<(), SerializeError<W::Error>> {
        write_uint_raw!(self, x, u64, 20)
    }

    fn write_u128_raw(&mut self, x: u128) -> Result<(), SerializeError<W::Error>> {
        write_uint_raw!(self, x, u128, 39)
    }

    fn write_i128_raw(&mut self, x: i128) -> Result<(), SerializeError<W::Error>> {
        if x < 0 { self.write(b"-")?; }
        self.write_u128_raw(x.unsigned_abs())
    }

    fn write_string_escaped(&mut self, bytes: &[u8]) -> Result<(), SerializeError<W::Error>> {
        self.write(b"\"")?;
        let mut i = 0;
        while i < bytes.len() {
            let ch = bytes[i];
            match ch {
                b'"'  => { self.write(b"\\\"")?; i += 1; }
                b'\\' => { self.write(b"\\\\")?; i += 1; }
                0x08  => { self.write(b"\\b")?;  i += 1; }
                0x09  => { self.write(b"\\t")?;  i += 1; }
                0x0A  => { self.write(b"\\n")?;  i += 1; }
                0x0B  => { self.escape_byte(ch)?;  i += 1; }
                0x0C  => { self.write(b"\\f")?;  i += 1; }
                0x0D  => { self.write(b"\\r")?;  i += 1; }
                0x20..=0x7E => {
                    // printable ASCII — emit a run at once
                    let start = i;
                    while i < bytes.len() && matches!(bytes[i], 0x20..=0x7E)
                        && bytes[i] != b'"' && bytes[i] != b'\\'
                    {
                        i += 1;
                    }
                    self.write(&bytes[start..i])?;
                }
                _ => {
                    let seq_len = utf8_char_len(ch);

                    // Fast path: clearly invalid lead or not enough bytes
                    if seq_len == 1 || i + seq_len > bytes.len() {
                        self.escape_byte(ch)?;
                        i += 1;
                        continue;
                    }

                    // Validate continuation bytes: must be 10xxxxxx
                    let mut valid = true;
                    for j in 1..seq_len {
                        if (bytes[i + j] & 0b1100_0000) != 0b1000_0000 {
                            valid = false;
                            break;
                        }
                    }

                    if valid {
                        // Structurally valid UTF-8 → passthrough
                        self.write(&bytes[i..i + seq_len])?;
                        i += seq_len;
                    } else {
                        // Invalid sequence → escape first byte only
                        self.escape_byte(ch)?;
                        i += 1;
                    }
                }
            }
        }
        self.write(b"\"")
    }

    // ---- public API ----

    pub fn null(&mut self) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write(b"null")?;
        self.element_end();
        Ok(())
    }

    pub fn boolean(&mut self, v: bool) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write(if v { b"true" } else { b"false" })?;
        self.element_end();
        Ok(())
    }

    pub fn integer(&mut self, v: i64) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write_integer_raw(v)?;
        self.element_end();
        Ok(())
    }

    pub fn float(&mut self, v: f64) -> Result<(), SerializeError<W::Error>> {
        if !v.is_finite() {
            return Err(SerializeError::InvalidValue("float must be finite (not NaN or Infinity)"));
        }
        // Format into a 32-byte stack buffer via core::fmt::Write — no alloc needed.
        let mut buf = [0u8; 32];
        let mut pos = 0usize;
        struct FloatBuf<'a>(&'a mut [u8], &'a mut usize);
        impl core::fmt::Write for FloatBuf<'_> {
            fn write_str(&mut self, s: &str) -> core::fmt::Result {
                let b = s.as_bytes();
                let end = *self.1 + b.len();
                if end > self.0.len() { return Err(core::fmt::Error); }
                self.0[*self.1..end].copy_from_slice(b);
                *self.1 = end;
                Ok(())
            }
        }
        let _ = core::fmt::write(&mut FloatBuf(&mut buf, &mut pos), format_args!("{v}"));
        self.element_begin()?;
        self.number_raw(&buf[..pos])?;
        self.element_end();
        Ok(())
    }

    pub fn unsigned(&mut self, v: u64) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write_u64_raw(v)?;
        self.element_end();
        Ok(())
    }

    pub fn integer128(&mut self, v: i128) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write_i128_raw(v)?;
        self.element_end();
        Ok(())
    }

    pub fn unsigned128(&mut self, v: u128) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write_u128_raw(v)?;
        self.element_end();
        Ok(())
    }

    /// Write a pre-formatted number string verbatim (no escaping).
    /// Use this for floats: format the number yourself and pass the bytes here.
    pub fn number_raw(&mut self, raw: &[u8]) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write(raw)?;
        self.element_end();
        Ok(())
    }

    pub fn string(&mut self, s: &str) -> Result<(), SerializeError<W::Error>> {
        self.string_bytes(s.as_bytes())
    }

    pub fn string_bytes(&mut self, b: &[u8]) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write_string_escaped(b)?;
        self.element_end();
        Ok(())
    }

    pub fn array_begin(&mut self) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write(b"[")?;
        self.push_scope(ScopeKind::Array)?;
        Ok(())
    }

    pub fn array_end(&mut self) -> Result<(), SerializeError<W::Error>> {
        self.write_closing(b"]")?;
        self.pop_scope();
        self.element_end();
        Ok(())
    }

    pub fn object_begin(&mut self) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        self.write(b"{")?;
        self.push_scope(ScopeKind::Object)?;
        Ok(())
    }

    pub fn member(&mut self, key: &str) -> Result<(), SerializeError<W::Error>> {
        self.member_bytes(key.as_bytes())
    }

    pub fn member_bytes(&mut self, key: &[u8]) -> Result<(), SerializeError<W::Error>> {
        self.element_begin()?;
        match self.current_scope() {
            Some(s) if s.kind == ScopeKind::Object && !s.key => {}
            _ => return Err(SerializeError::InvalidState),
        }
        self.write_string_escaped(key)?;
        self.write(b":")?;
        if let Some(s) = self.current_scope() {
            s.tail = true;
            s.key = true;
        }
        Ok(())
    }

    pub fn object_end(&mut self) -> Result<(), SerializeError<W::Error>> {
        self.write_closing(b"}")?;
        self.pop_scope();
        self.element_end();
        Ok(())
    }

    fn escape_byte(&mut self, ch: u8) -> Result<(), SerializeError<W::Error>> {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        self.write(b"\\u00")?;
        self.write(&[
            HEX[(ch >> 4) as usize],
            HEX[(ch & 0x0F) as usize],
        ])?;
        Ok(())
    }
}

fn utf8_char_len(first_byte: u8) -> usize {
    if first_byte & 0x80 == 0 { 1 }
    else if first_byte & 0xE0 == 0xC0 { 2 }
    else if first_byte & 0xF0 == 0xE0 { 3 }
    else if first_byte & 0xF8 == 0xF0 { 4 }
    else { 1 } // invalid lead byte, treat as single
}

/// Trait for types that can serialize themselves as JSON.
pub trait Serialize {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>>;
}

impl Serialize for bool {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.boolean(*self)
    }
}

macro_rules! impl_integer {
    ($($t:ty),*) => {$(
        impl Serialize for $t {
            fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
                ser.integer(*self as i64)
            }
        }
    )*};
}
impl_integer!(i8, i16, i32, i64, u8, u16, u32, isize);

// u64 and usize need unsigned() to avoid silent truncation of values > i64::MAX.
impl Serialize for u64 {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.unsigned(*self)
    }
}
impl Serialize for usize {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.unsigned(*self as u64)
    }
}
impl Serialize for i128 {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.integer128(*self)
    }
}
impl Serialize for u128 {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.unsigned128(*self)
    }
}

impl Serialize for str {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.string(self)
    }
}

impl Serialize for &str {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.string(self)
    }
}

#[cfg(feature = "alloc")]
impl Serialize for alloc::string::String {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.string(self)
    }
}

impl<T: Serialize> Serialize for Option<T> {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        match self {
            None => ser.null(),
            Some(v) => v.serialize(ser),
        }
    }
}

impl<T: Serialize> Serialize for [T] {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.array_begin()?;
        for item in self {
            item.serialize(ser)?;
        }
        ser.array_end()
    }
}

impl<T: Serialize, const N: usize> Serialize for [T; N] {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        self.as_slice().serialize(ser)
    }
}

impl Serialize for f32 {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.float(*self as f64)
    }
}

impl Serialize for f64 {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.float(*self as f64)
    }
}

#[cfg(feature = "alloc")]
impl<T: Serialize> Serialize for alloc::vec::Vec<T> {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        self.as_slice().serialize(ser)
    }
}

#[cfg(feature = "alloc")]
impl<T: Serialize> Serialize for alloc::boxed::Box<T> {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        (**self).serialize(ser)
    }
}

macro_rules! impl_serialize_map {
    ($($bound:tt)*) => {
        fn serialize<__W: Write>(&self, ser: &mut Serializer<__W>) -> Result<(), SerializeError<__W::Error>> {
            ser.object_begin()?;
            for (k, v) in self {
                ser.member(k.as_ref())?;
                v.serialize(ser)?;
            }
            ser.object_end()
        }
    };
}

#[cfg(feature = "alloc")]
impl<K: AsRef<str>, V: Serialize> Serialize for alloc::collections::BTreeMap<K, V> {
    impl_serialize_map!();
}

#[cfg(feature = "std")]
impl<K: AsRef<str> + Eq + std::hash::Hash, V: Serialize> Serialize
    for std::collections::HashMap<K, V>
{
    impl_serialize_map!();
}

#[cfg(feature = "arrayvec")]
impl<T: Serialize, const N: usize> Serialize for arrayvec::ArrayVec<T, N> {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        self.as_slice().serialize(ser)
    }
}

#[cfg(feature = "arrayvec")]
impl<const N: usize> Serialize for arrayvec::ArrayString<N> {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.string(self.as_str())
    }
}

impl Serialize for () {
    fn serialize<W: Write>(&self, ser: &mut Serializer<W>) -> Result<(), SerializeError<W::Error>> {
        ser.null()
    }
}

// ---- Convenience free functions ----

// Shared implementation for all stack-buffer variants; `pp=0` for compact, `pp>0` for pretty.
fn stringify_sized_impl<'buf>(
    buf: &'buf mut [u8],
    pp: usize,
    f: impl FnOnce(&mut Serializer<&mut crate::write::SliceWriter<'_>>) -> Result<(), SerializeError<WriteError>>,
) -> Result<&'buf str, SerializeError<WriteError>> {
    let mut w = crate::write::SliceWriter::new(buf);
    let mut ser = Serializer::with_pretty(&mut w, pp);
    f(&mut ser)?;
    let len = w.pos();
    core::str::from_utf8(&buf[..len]).map_err(|e| SerializeError::InvalidUtf8(e.valid_up_to()))
}

/// Serialize via closure into a stack-allocated `[u8; N]`.
/// Returns `(buffer, bytes_written)`.
///
/// # Example
/// ```
/// let mut buf = [0u8; 32];
/// let json = nanojson::stringify_sized_as(&mut buf, |s| {
///     s.object_begin()?;
///     s.member("n")?; s.integer(7)?;
///     s.object_end()
/// }).unwrap();
/// assert_eq!(json, "{\"n\":7}");
/// ```
#[inline]
pub fn stringify_sized_as<'buf>(
    buf: &'buf mut [u8],
    f: impl FnOnce(&mut Serializer<&mut crate::write::SliceWriter<'_>>) -> Result<(), SerializeError<WriteError>>,
) -> Result<&'buf str, SerializeError<WriteError>> {
    stringify_sized_impl(buf, 0, f)
}

/// Serialize a `T: Serialize` value into a stack-allocated `[u8; N]` buffer.
///
/// # Example
/// ```
/// let mut buf = [0u8; 32];
/// let json = nanojson::stringify_sized(&mut buf, &42i64).unwrap();
/// assert_eq!(json, "42");
/// ```
#[inline]
pub fn stringify_sized<'buf, T: Serialize>(
    buf: &'buf mut [u8],
    val: &T,
) -> Result<&'buf str, SerializeError<WriteError>> {
    stringify_sized_as(buf, |s| val.serialize(s))
}

/// Serialize via closure into a stack-allocated `[u8; N]` buffer with pretty-printing.
///
/// # Example
/// ```
/// let mut buf = [0u8; 64];
/// let json = nanojson::stringify_sized_pretty_as(&mut buf, 2, |s| {
///     s.object_begin()?;
///     s.member("x")?; s.integer(1)?;
///     s.object_end()
/// }).unwrap();
/// assert_eq!(json, "{\n  \"x\": 1\n}");
/// ```
#[inline]
pub fn stringify_sized_pretty_as<'buf>(
    buf: &'buf mut [u8],
    indent: usize,
    f: impl FnOnce(&mut Serializer<&mut crate::write::SliceWriter<'_>>) -> Result<(), SerializeError<WriteError>>,
) -> Result<&'buf str, SerializeError<WriteError>> {
    stringify_sized_impl(buf, indent, f)
}

/// Serialize a `T: Serialize` value into a stack-allocated `[u8; N]` buffer with pretty-printing.
///
/// # Example
/// ```
/// # use nanojson::Serialize;
/// # #[cfg(feature = "derive")] {
/// #[derive(nanojson::Serialize)]
/// struct Point { x: i64, y: i64 }
/// let mut buf = [0u8; 64];
/// let json = nanojson::stringify_sized_pretty(&mut buf, 2, &Point { x: 1, y: 2 }).unwrap();
/// assert_eq!(json, "{\n  \"x\": 1,\n  \"y\": 2\n}");
/// # }
/// ```
#[inline]
pub fn stringify_sized_pretty<'buf, T: Serialize>(
    buf: &'buf mut [u8],
    indent: usize,
    val: &T,
) -> Result<&'buf str, SerializeError<WriteError>> {
    stringify_sized_pretty_as(buf, indent, |s| val.serialize(s))
}

/// Count the bytes that a closure would produce without writing anything.
/// Returns the byte count; returns 0 if `DepthExceeded` is hit.
///
/// # Example
/// ```
/// let n = nanojson::measure(|s| {
///     s.object_begin()?;
///     s.member("x")?; s.integer(1)?;
///     s.object_end()
/// });
/// assert_eq!(n, 7); // {"x":1}
/// ```
#[inline]
pub fn measure(
    f: impl FnOnce(&mut Serializer<&mut crate::write::SizeCounter>) -> Result<(), SerializeError<core::convert::Infallible>>,
) -> usize {
    let mut counter = crate::write::SizeCounter::new();
    let mut ser = Serializer::new(&mut counter);
    let _ = f(&mut ser);
    counter.count
}

// Shared implementation for all heap-allocated variants; `pp=0` for compact, `pp>0` for pretty.
#[cfg(feature = "std")]
fn serialize_to_vec(
    pp: usize,
    f: impl FnOnce(&mut Serializer<std::vec::Vec<u8>>) -> Result<(), SerializeError<core::convert::Infallible>>,
) -> Result<std::vec::Vec<u8>, SerializeError<core::convert::Infallible>> {
    let mut ser: Serializer<_> = Serializer::with_pretty(std::vec::Vec::new(), pp);
    f(&mut ser)?;
    Ok(ser.into_writer())
}

#[cfg(feature = "std")]
fn vec_to_string(
    vec: std::vec::Vec<u8>,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    std::string::String::from_utf8(vec)
        .map_err(|e| SerializeError::InvalidUtf8(e.utf8_error().error_len().unwrap_or(0)))
}

/// Serialize a value into a heap-allocated [`String`].
/// Only fails if nesting exceeds the default depth limit (32).
///
/// # Example
/// ```
/// let json = nanojson::stringify(&[1i64, 2, 3]).unwrap();
/// assert_eq!(json, "[1,2,3]");
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn stringify<T: Serialize>(
    val: &T,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    stringify_as(|s| val.serialize(s))
}

/// Serialize via closure into a heap-allocated [`String`].
/// The output buffer grows as needed; no size choice required.
/// Only fails if nesting exceeds the default depth limit (32).
///
/// # Example
/// ```
/// let json = nanojson::stringify_as(|s| {
///     s.object_begin()?;
///     s.member("x")?; s.integer(1)?;
///     s.object_end()
/// }).unwrap();
/// assert_eq!(json, r#"{"x":1}"#);
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn stringify_as(
    f: impl FnOnce(&mut Serializer<std::vec::Vec<u8>>) -> Result<(), SerializeError<core::convert::Infallible>>,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    vec_to_string(serialize_to_vec(0, f)?)
}

/// Serialize a value into a pretty-printed heap-allocated [`String`].
/// Only fails if nesting exceeds the default depth limit (32).
///
/// # Example
/// ```
/// let json = nanojson::stringify_pretty(2, &[1i64, 2, 3]).unwrap();
/// assert_eq!(json, "[\n  1,\n  2,\n  3\n]");
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn stringify_pretty<T: Serialize>(
    indent: usize,
    val: &T,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    stringify_pretty_as(indent, |s| val.serialize(s))
}

/// Serialize via closure into a pretty-printed heap-allocated [`String`].
/// Only fails if nesting exceeds the default depth limit (32).
///
/// # Example
/// ```
/// let json = nanojson::stringify_pretty_as(2, |s| {
///     s.object_begin()?;
///     s.member("x")?; s.integer(1)?;
///     s.object_end()
/// }).unwrap();
/// assert_eq!(json, "{\n  \"x\": 1\n}");
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn stringify_pretty_as(
    indent: usize,
    f: impl FnOnce(&mut Serializer<std::vec::Vec<u8>>) -> Result<(), SerializeError<core::convert::Infallible>>,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    vec_to_string(serialize_to_vec(indent, f)?)
}

// ---- Smart pretty-print ----

// Apply smart formatting to compact JSON bytes; returns the formatted output.
#[cfg(feature = "std")]
fn apply_smart_format(
    compact: std::vec::Vec<u8>,
    line_width: usize,
    indent: usize,
) -> std::vec::Vec<u8> {
    if compact.is_empty() { return compact };
    let mut out = std::vec::Vec::with_capacity(compact.len() * 2);
    smart_format(&compact, &mut 0, &mut out, line_width, indent, 0);
    out
}

/// Advance `pos` from the opening `"` past the closing `"`, handling `\"` escapes.
#[cfg(feature = "std")]
fn skip_string_end(input: &[u8], pos: &mut usize) {
    *pos += 1; // skip opening '"'
    loop {
        match input[*pos] {
            b'\\' => *pos += 2, // skip escape + next byte
            b'"'  => { *pos += 1; return; }
            _     => *pos += 1,
        }
    }
}

/// Return the index one past the closing `}` or `]` of the container starting at `start`.
#[cfg(feature = "std")]
fn find_container_end(input: &[u8], start: usize) -> usize {
    let mut pos = start + 1;
    let mut depth = 1usize;
    loop {
        match input[pos] {
            b'"'        => skip_string_end(input, &mut pos),
            b'{' | b'[' => { depth += 1; pos += 1; }
            b'}' | b']' => {
                pos += 1;
                depth -= 1;
                if depth == 0 { return pos; }
            }
            _           => pos += 1,
        }
    }
}

/// Return the index one past the end of the JSON value starting at `start`.
#[cfg(feature = "std")]
fn find_value_end(input: &[u8], start: usize) -> usize {
    match input[start] {
        b'{' | b'[' => find_container_end(input, start),
        b'"' => {
            let mut pos = start;
            skip_string_end(input, &mut pos);
            pos
        }
        b't' => start + 4,
        b'f' => start + 5,
        b'n' => start + 4,
        _ => {
            // number
            let mut pos = start;
            while pos < input.len() {
                match input[pos] {
                    b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-' => pos += 1,
                    _ => break,
                }
            }
            pos
        }
    }
}

/// Count the bytes that `copy_with_spacing` would produce for `input[start..end]`.
/// (Adds one space after each `,` or `:` not inside a string.)
#[cfg(feature = "std")]
fn spaced_len(input: &[u8], start: usize, end: usize) -> usize {
    let mut len = end - start;
    let mut pos = start;
    while pos < end {
        match input[pos] {
            b'"'        => skip_string_end(input, &mut pos),
            b':' | b',' => { len += 1; pos += 1; }
            _           => pos += 1,
        }
    }
    len
}

/// Copy a compact container `input[start..end]` to `out`, inserting a space after
/// each `:` and `,` that is not inside a string.
#[cfg(feature = "std")]
fn copy_with_spacing(input: &[u8], start: usize, end: usize, out: &mut std::vec::Vec<u8>) {
    let mut pos = start;
    while pos < end {
        match input[pos] {
            b'"' => {
                let s = pos;
                skip_string_end(input, &mut pos);
                out.extend_from_slice(&input[s..pos]);
            }
            b':' | b',' => {
                out.push(input[pos]);
                out.push(b' ');
                pos += 1;
            }
            b => {
                out.push(b);
                pos += 1;
            }
        }
    }
}

/// Write `depth * indent` space characters.
#[cfg(feature = "std")]
fn write_indent(out: &mut std::vec::Vec<u8>, depth: usize, indent: usize) {
    let n = depth * indent;
    out.resize(out.len() + n, b' ');
}

/// Measure the display width and inlineability of the JSON value at `input[scan]`.
/// Returns `(display_len, is_inline)`:
///   - `display_len`: rendered byte width if kept on one line (0 if not inline)
///   - `is_inline`: true if the value fits in `line_width` or is a scalar
#[cfg(feature = "std")]
fn measure_value(input: &[u8], scan: usize, line_width: usize) -> (usize, bool) {
    let val_end = find_value_end(input, scan);
    let is_container = matches!(input[scan], b'{' | b'[');
    let inline = !is_container || val_end - scan <= line_width;
    let display = if inline { spaced_len(input, scan, val_end) } else { 0 };
    (display, inline)
}

/// Expand the object or array at `input[*pos]` into multi-line form with flow packing.
///
/// Short elements (value compact_len ≤ `line_width`) are packed onto lines until the
/// line would overflow, then wrapped. Elements whose value requires multi-line expansion
/// always occupy their own line(s).
#[cfg(feature = "std")]
fn format_expanded(
    input: &[u8],
    pos: &mut usize,
    out: &mut std::vec::Vec<u8>,
    line_width: usize,
    indent: usize,
    depth: usize,
) {
    let is_object = input[*pos] == b'{';
    let open = input[*pos];
    let close = if is_object { b'}' } else { b']' };
    out.push(open);
    *pos += 1;

    // Empty container — shouldn't normally reach here since smart_format would keep
    // {} / [] compact, but handle gracefully.
    if input[*pos] == close {
        out.push(close);
        *pos += 1;
        return;
    }

    out.push(b'\n');
    write_indent(out, depth + 1, indent);

    let base_indent = (depth + 1) * indent;
    let mut current_col = base_indent;
    let mut first = true;

    while input[*pos] != close {
        // ---- Measure this element without advancing *pos ----
        // `elem_display_len`: rendered byte width if placed on one line.
        // `value_is_inline`: whether the value itself fits in line_width.
        let (elem_display_len, value_is_inline) = {
            let mut scan = *pos;
            if is_object {
                let key_start = scan;
                skip_string_end(input, &mut scan); // past key
                let key_display = spaced_len(input, key_start, scan);
                scan += 1; // past ':'
                let (val_display, val_inline) = measure_value(input, scan, line_width);
                (key_display + 2 + val_display, val_inline) // +2 for ": "
            } else {
                measure_value(input, scan, line_width)
            }
        };

        // ---- Decide placement ----
        let sep = if first { 0 } else { 2 }; // len of ", "
        let needs_new_line = !first
            && (!value_is_inline || current_col + sep + elem_display_len > line_width);

        if needs_new_line {
            out.extend_from_slice(b",\n");
            write_indent(out, depth + 1, indent);
            current_col = base_indent;
        } else if !first {
            out.extend_from_slice(b", ");
            current_col += 2;
        }

        // ---- Write the element, advancing *pos ----
        if is_object {
            let key_start = *pos;
            skip_string_end(input, pos);
            out.extend_from_slice(&input[key_start..*pos]);
            out.extend_from_slice(b": ");
            *pos += 1; // skip ':'
        }
        if value_is_inline {
            let val_end = find_value_end(input, *pos);
            copy_with_spacing(input, *pos, val_end, out);
            *pos = val_end;
            current_col += elem_display_len;
        } else {
            format_expanded(input, pos, out, line_width, indent, depth + 1);
            // After a multi-line value, force the next element onto a new line.
            current_col = line_width.saturating_add(1);
        }

        if input[*pos] == b',' {
            *pos += 1;
        }
        first = false;
    }

    out.push(b'\n');
    write_indent(out, depth, indent);
    out.push(close);
    *pos += 1;
}

/// Recursively smart-format the JSON value at `input[*pos]`.
/// Containers whose compact length ≤ `line_width` are kept on one line;
/// larger containers are expanded to multi-line with `indent`-space indentation.
#[cfg(feature = "std")]
fn smart_format(
    input: &[u8],
    pos: &mut usize,
    out: &mut std::vec::Vec<u8>,
    line_width: usize,
    indent: usize,
    depth: usize,
) {
    match input[*pos] {
        b'{' | b'[' => {
            let end = find_container_end(input, *pos);
            if end - *pos <= line_width {
                copy_with_spacing(input, *pos, end, out);
                *pos = end;
            } else {
                format_expanded(input, pos, out, line_width, indent, depth);
            }
        }
        _ => {
            let end = find_value_end(input, *pos);
            out.extend_from_slice(&input[*pos..end]);
            *pos = end;
        }
    }
}

/// Serialize via closure into a smart-pretty-printed heap-allocated [`String`].
///
/// Each object or array whose compact JSON length is ≤ `line_width` bytes is kept
/// on a single line; larger containers are expanded to multi-line with `indent`-space
/// indentation applied recursively.
///
/// # Example
/// ```
/// let json = nanojson::stringify_compact_as(20, 2, |s| {
///     s.object_begin()?;
///     s.member("x")?; s.integer(1)?;
///     s.member("ys")?;
///     s.array_begin()?;
///         s.integer(10)?; s.integer(20)?; s.integer(30)?;
///     s.array_end()?;
///     s.object_end()
/// }).unwrap();
/// // {"x":1,"ys":[10,20,30]} is 22 bytes > 20 → outer expands
/// // [10,20,30] is 10 bytes ≤ 20 → inner stays on one line
/// assert_eq!(json, "{\n  \"x\": 1,\n  \"ys\": [10, 20, 30]\n}");
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn stringify_compact_as(
    line_width: usize,
    indent: usize,
    f: impl FnOnce(&mut Serializer<std::vec::Vec<u8>>) -> Result<(), SerializeError<core::convert::Infallible>>,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    vec_to_string(apply_smart_format(serialize_to_vec(0, f)?, line_width, indent))
}

/// Serialize a value into a smart-pretty-printed heap-allocated [`String`].
///
/// Each object or array whose compact JSON length is ≤ `line_width` bytes is kept
/// on a single line; larger containers are expanded to multi-line with `indent`-space
/// indentation applied recursively.
///
/// # Example
/// ```
/// let json = nanojson::stringify_compact(&[1i64, 2, 3], 40, 2).unwrap();
/// assert_eq!(json, "[1, 2, 3]");
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn stringify_compact<T: Serialize>(
    val: &T,
    line_width: usize,
    indent: usize,
) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
    stringify_compact_as(line_width, indent, |s| val.serialize(s))
}

/// An imperative-style smart compact pretty-printer.
///
/// Equivalent to [`stringify_compact_as`] but without the closure — useful when
/// the JSON structure is not known until runtime or when you prefer to call serializer
/// methods directly rather than through a closure.
///
/// Internally serializes to compact JSON, then smart-formats the result on [`finish`].
/// All [`Serializer`] methods are available via [`Deref`] / [`DerefMut`].
///
/// # Example
/// ```
/// use nanojson::SmartSerializer;
///
/// let mut ser = SmartSerializer::with_compact(40, 2);
/// ser.array_begin()?;
/// for i in 1i64..=3 { ser.integer(i)?; }
/// ser.array_end()?;
/// let json = ser.finish()?;
/// assert_eq!(json, "[1, 2, 3]");
/// # Ok::<(), nanojson::SerializeError<core::convert::Infallible>>(())
/// ```
///
/// [`finish`]: SmartSerializer::finish
/// [`Deref`]: core::ops::Deref
/// [`DerefMut`]: core::ops::DerefMut
#[cfg(feature = "std")]
pub struct SmartSerializer {
    inner: Serializer<std::vec::Vec<u8>>,
    line_width: usize,
    indent: usize,
}

#[cfg(feature = "std")]
impl SmartSerializer {
    /// Create a new smart compact pretty-printer with the given `line_width` and `indent`.
    pub fn with_compact(line_width: usize, indent: usize) -> Self {
        Self { inner: Serializer::new(std::vec::Vec::new()), line_width, indent }
    }

    /// Finish serialization, smart-format the output, and return the resulting [`String`].
    pub fn finish(self) -> Result<std::string::String, SerializeError<core::convert::Infallible>> {
        vec_to_string(apply_smart_format(self.inner.into_writer(), self.line_width, self.indent))
    }
}

#[cfg(feature = "std")]
impl core::ops::Deref for SmartSerializer {
    type Target = Serializer<std::vec::Vec<u8>>;
    fn deref(&self) -> &Self::Target { &self.inner }
}

#[cfg(feature = "std")]
impl core::ops::DerefMut for SmartSerializer {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner }
}