nanoserde/
serde_json.rs

1use core::hash::Hash;
2use core::str::Chars;
3
4use alloc::boxed::Box;
5use alloc::collections::{BTreeSet, LinkedList};
6use alloc::format;
7use alloc::string::{String, ToString};
8use alloc::vec::Vec;
9
10#[cfg(feature = "no_std")]
11use hashbrown::{HashMap, HashSet};
12
13#[cfg(not(feature = "no_std"))]
14use std::collections::{HashMap, HashSet};
15
16/// The internal state of a JSON serialization.
17pub struct SerJsonState {
18    pub out: String,
19}
20
21impl SerJsonState {
22    pub fn indent(&mut self, _d: usize) {
23        //for _ in 0..d {
24        //    self.out.push_str("    ");
25        //}
26    }
27
28    pub fn field(&mut self, d: usize, field: &str) {
29        self.indent(d);
30        self.out.push('"');
31        self.out.push_str(field);
32        self.out.push('"');
33        self.out.push(':');
34    }
35
36    pub fn label(&mut self, label: &str) {
37        self.out.push('"');
38        self.out.push_str(label);
39        self.out.push('"');
40    }
41
42    pub fn conl(&mut self) {
43        self.out.push(',')
44    }
45
46    pub fn st_pre(&mut self) {
47        self.out.push('{');
48    }
49
50    pub fn st_post(&mut self, d: usize) {
51        self.indent(d);
52        self.out.push('}');
53    }
54}
55
56/// A trait for objects that can be serialized to JSON.
57pub trait SerJson {
58    /// Serialize Self to a JSON string.
59    ///
60    /// This is a convenient wrapper around `ser_json`.
61    fn serialize_json(&self) -> String {
62        let mut s = SerJsonState { out: String::new() };
63        self.ser_json(0, &mut s);
64        s.out
65    }
66
67    /// Serialize Self to a JSON string.
68    ///
69    /// ```rust
70    /// # use nanoserde::*;
71    /// let mut s = SerJsonState { out: String::new() };
72    /// 42u32.ser_json(0, &mut s);
73    /// assert_eq!(s.out, "42");
74    /// ```
75    fn ser_json(&self, d: usize, s: &mut SerJsonState);
76}
77
78/// A trait for objects that can be deserialized from JSON.
79pub trait DeJson: Sized {
80    /// Parse Self from the input string.
81    ///
82    /// This is a convenient wrapper around `de_json`.
83    fn deserialize_json(input: &str) -> Result<Self, DeJsonErr> {
84        let mut state = DeJsonState::default();
85        let mut chars = input.chars();
86        state.next(&mut chars);
87        state.next_tok(&mut chars)?;
88        DeJson::de_json(&mut state, &mut chars)
89    }
90
91    /// Parse Self from the input string.
92    ///
93    /// ```rust
94    /// # use nanoserde::*;
95    /// let mut state = DeJsonState::default();
96    /// let mut chars = "42".chars();
97    /// state.next(&mut chars);
98    /// state.next_tok(&mut chars).unwrap();
99    /// let out = u32::de_json(&mut state, &mut chars).unwrap();
100    /// assert_eq!(out, 42);
101    /// ```
102    fn de_json(state: &mut DeJsonState, input: &mut Chars) -> Result<Self, DeJsonErr>;
103}
104
105/// A JSON parsed token.
106#[derive(PartialEq, Debug)]
107pub enum DeJsonTok {
108    Str,
109    Char(char),
110    U64(u64),
111    I64(i64),
112    F64(f64),
113    Bool(bool),
114    BareIdent,
115    Null,
116    Colon,
117    CurlyOpen,
118    CurlyClose,
119    BlockOpen,
120    BlockClose,
121    Comma,
122    Bof,
123    Eof,
124}
125
126impl Default for DeJsonTok {
127    fn default() -> Self {
128        DeJsonTok::Bof
129    }
130}
131
132/// The internal state of a JSON deserialization.
133#[derive(Default)]
134pub struct DeJsonState {
135    pub cur: char,
136    pub tok: DeJsonTok,
137    pub strbuf: String,
138    pub numbuf: String,
139    pub identbuf: String,
140    pub line: usize,
141    pub col: usize,
142}
143
144/// The error message when failing to deserialize a JSON string.
145#[derive(Clone)]
146pub struct DeJsonErr {
147    pub msg: String,
148    pub line: usize,
149    pub col: usize,
150}
151
152impl core::fmt::Debug for DeJsonErr {
153    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
154        write!(
155            f,
156            "Json Deserialize error: {}, line:{} col:{}",
157            self.msg,
158            self.line + 1,
159            self.col + 1
160        )
161    }
162}
163
164impl core::fmt::Display for DeJsonErr {
165    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
166        core::fmt::Debug::fmt(self, f)
167    }
168}
169
170#[cfg(feature = "no_std")]
171impl core::error::Error for DeJsonErr {}
172
173#[cfg(not(feature = "no_std"))]
174impl std::error::Error for DeJsonErr {}
175
176impl DeJsonState {
177    pub fn next(&mut self, i: &mut Chars) {
178        if let Some(c) = i.next() {
179            self.cur = c;
180            if self.cur == '\n' {
181                self.line += 1;
182                self.col = 0;
183            } else {
184                self.col += 1;
185            }
186        } else {
187            self.cur = '\0';
188        }
189    }
190
191    pub fn err_exp(&self, name: &str) -> DeJsonErr {
192        DeJsonErr {
193            msg: format!("Unexpected key {}", name),
194            line: self.line,
195            col: self.col,
196        }
197    }
198
199    pub fn err_nf(&self, name: &str) -> DeJsonErr {
200        DeJsonErr {
201            msg: format!("Key not found {}", name),
202            line: self.line,
203            col: self.col,
204        }
205    }
206
207    pub fn err_enum(&self, name: &str) -> DeJsonErr {
208        DeJsonErr {
209            msg: format!("Enum not defined {}", name),
210            line: self.line,
211            col: self.col,
212        }
213    }
214
215    pub fn err_token(&self, what: &str) -> DeJsonErr {
216        DeJsonErr {
217            msg: format!("Unexpected token {:?} expected {} ", self.tok, what),
218            line: self.line,
219            col: self.col,
220        }
221    }
222
223    pub fn err_range(&self, what: &str) -> DeJsonErr {
224        DeJsonErr {
225            msg: format!("Value out of range {} ", what),
226            line: self.line,
227            col: self.col,
228        }
229    }
230
231    pub fn err_type(&self, what: &str) -> DeJsonErr {
232        DeJsonErr {
233            msg: format!("Token wrong type {} ", what),
234            line: self.line,
235            col: self.col,
236        }
237    }
238
239    pub fn err_parse(&self, what: &str) -> DeJsonErr {
240        DeJsonErr {
241            msg: format!("Cannot parse {} ", what),
242            line: self.line,
243            col: self.col,
244        }
245    }
246
247    pub fn eat_comma_block(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
248        match self.tok {
249            DeJsonTok::Comma => {
250                self.next_tok(i)?;
251                Ok(())
252            }
253            DeJsonTok::BlockClose => Ok(()),
254            _ => Err(self.err_token(", or ]")),
255        }
256    }
257
258    pub fn whole_field(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
259        match self.tok {
260            DeJsonTok::F64 { .. }
261            | DeJsonTok::I64 { .. }
262            | DeJsonTok::Str
263            | DeJsonTok::U64 { .. }
264            | DeJsonTok::Bool { .. }
265            | DeJsonTok::Null => {
266                self.next_tok(i)?;
267                Ok(())
268            }
269            DeJsonTok::BlockOpen | DeJsonTok::CurlyOpen => {
270                let mut open_brackets = 0;
271
272                loop {
273                    if let DeJsonTok::BlockOpen | DeJsonTok::CurlyOpen = self.tok {
274                        open_brackets += 1;
275                    }
276
277                    if let DeJsonTok::BlockClose | DeJsonTok::CurlyClose = self.tok {
278                        open_brackets -= 1;
279                    }
280
281                    self.next_tok(i)?;
282
283                    if open_brackets == 0 {
284                        break;
285                    }
286                }
287                Ok(())
288            }
289            _ => unimplemented!("{:?}", self.tok),
290        }
291    }
292
293    pub fn eat_comma_curly(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
294        match self.tok {
295            DeJsonTok::Comma => {
296                self.next_tok(i)?;
297                Ok(())
298            }
299            DeJsonTok::CurlyClose => Ok(()),
300            _ => Err(self.err_token(", or }")),
301        }
302    }
303
304    pub fn colon(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
305        match self.tok {
306            DeJsonTok::Colon => {
307                self.next_tok(i)?;
308                Ok(())
309            }
310            _ => Err(self.err_token(":")),
311        }
312    }
313
314    pub fn string(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
315        match &mut self.tok {
316            DeJsonTok::Str => {
317                self.next_tok(i)?;
318                Ok(())
319            }
320            _ => Err(self.err_token("String")),
321        }
322    }
323
324    pub fn next_colon(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
325        self.next_tok(i)?;
326        self.colon(i)?;
327        Ok(())
328    }
329
330    pub fn next_str(&mut self) -> Option<()> {
331        if let DeJsonTok::Str = &mut self.tok {
332            //let mut s = String::new();
333            //core::mem::swap(&mut s, name);
334            Some(())
335        } else {
336            None
337        }
338    }
339
340    pub fn block_open(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
341        if self.tok == DeJsonTok::BlockOpen {
342            self.next_tok(i)?;
343            return Ok(());
344        }
345        Err(self.err_token("["))
346    }
347
348    pub fn block_close(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
349        if self.tok == DeJsonTok::BlockClose {
350            self.next_tok(i)?;
351            return Ok(());
352        }
353        Err(self.err_token("]"))
354    }
355
356    pub fn curly_open(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
357        if self.tok == DeJsonTok::CurlyOpen {
358            self.next_tok(i)?;
359            return Ok(());
360        }
361        Err(self.err_token("{"))
362    }
363
364    pub fn curly_close(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
365        if self.tok == DeJsonTok::CurlyClose {
366            self.next_tok(i)?;
367            return Ok(());
368        }
369        Err(self.err_token("}"))
370    }
371
372    pub fn u64_range(&mut self, max: u64) -> Result<u64, DeJsonErr> {
373        if let DeJsonTok::U64(value) = self.tok {
374            if value > max {
375                return Err(self.err_range(&format!("{}>{}", value, max)));
376            }
377            return Ok(value);
378        }
379        Err(self.err_token("unsigned integer"))
380    }
381
382    pub fn i64_range(&mut self, min: i64, max: i64) -> Result<i64, DeJsonErr> {
383        if let DeJsonTok::I64(value) = self.tok {
384            if value < min {
385                return Err(self.err_range(&format!("{}<{}", value, min)));
386            }
387            return Ok(value);
388        }
389        if let DeJsonTok::U64(value) = self.tok {
390            if value as i64 > max {
391                return Err(self.err_range(&format!("{}>{}", value, max)));
392            }
393            return Ok(value as i64);
394        }
395        Err(self.err_token("signed integer"))
396    }
397
398    pub fn as_f64(&mut self) -> Result<f64, DeJsonErr> {
399        if let DeJsonTok::I64(value) = self.tok {
400            return Ok(value as f64);
401        }
402        if let DeJsonTok::U64(value) = self.tok {
403            return Ok(value as f64);
404        }
405        if let DeJsonTok::F64(value) = self.tok {
406            return Ok(value);
407        }
408        Err(self.err_token("floating point"))
409    }
410
411    pub fn as_bool(&mut self) -> Result<bool, DeJsonErr> {
412        if let DeJsonTok::Bool(value) = self.tok {
413            return Ok(value);
414        }
415        Err(self.err_token("boolean"))
416    }
417
418    pub fn as_string(&mut self) -> Result<String, DeJsonErr> {
419        if let DeJsonTok::Str = &mut self.tok {
420            let mut val = String::new();
421            core::mem::swap(&mut val, &mut self.strbuf);
422            return Ok(val);
423        }
424        Err(self.err_token("string"))
425    }
426
427    pub fn next_tok(&mut self, i: &mut Chars) -> Result<(), DeJsonErr> {
428        while self.cur == '\n' || self.cur == '\r' || self.cur == '\t' || self.cur == ' ' {
429            self.next(i);
430        }
431        if self.cur == '\0' {
432            self.tok = DeJsonTok::Eof;
433            return Ok(());
434        }
435        match self.cur {
436            ':' => {
437                self.next(i);
438                self.tok = DeJsonTok::Colon;
439                return Ok(());
440            }
441            ',' => {
442                self.next(i);
443                self.tok = DeJsonTok::Comma;
444                return Ok(());
445            }
446            '[' => {
447                self.next(i);
448                self.tok = DeJsonTok::BlockOpen;
449                return Ok(());
450            }
451            ']' => {
452                self.next(i);
453                self.tok = DeJsonTok::BlockClose;
454                return Ok(());
455            }
456            '{' => {
457                self.next(i);
458                self.tok = DeJsonTok::CurlyOpen;
459                return Ok(());
460            }
461            '}' => {
462                self.next(i);
463                self.tok = DeJsonTok::CurlyClose;
464                return Ok(());
465            }
466            '-' | '+' | '0'..='9' => {
467                self.numbuf.truncate(0);
468                let is_neg = if self.cur == '-' || self.cur == '+' {
469                    let sign = self.cur;
470                    self.numbuf.push(self.cur);
471                    self.next(i);
472                    sign == '-'
473                } else {
474                    false
475                };
476                while self.cur >= '0' && self.cur <= '9' {
477                    self.numbuf.push(self.cur);
478                    self.next(i);
479                }
480                let mut is_float = false;
481                if self.cur == '.' {
482                    is_float = true;
483                    self.numbuf.push(self.cur);
484                    self.next(i);
485                    while self.cur >= '0' && self.cur <= '9' {
486                        self.numbuf.push(self.cur);
487                        self.next(i);
488                    }
489                }
490                if self.cur == 'e' || self.cur == 'E' {
491                    is_float = true;
492                    self.numbuf.push(self.cur);
493                    self.next(i);
494                    if self.cur == '-' {
495                        self.numbuf.push(self.cur);
496                        self.next(i);
497                    }
498                    while self.cur >= '0' && self.cur <= '9' {
499                        self.numbuf.push(self.cur);
500                        self.next(i);
501                    }
502                }
503                if is_float {
504                    if let Ok(num) = self.numbuf.parse() {
505                        self.tok = DeJsonTok::F64(num);
506                        return Ok(());
507                    } else {
508                        return Err(self.err_parse("number"));
509                    }
510                } else {
511                    if is_neg {
512                        if let Ok(num) = self.numbuf.parse() {
513                            self.tok = DeJsonTok::I64(num);
514                            return Ok(());
515                        } else {
516                            return Err(self.err_parse("number"));
517                        }
518                    }
519                    if let Ok(num) = self.numbuf.parse() {
520                        self.tok = DeJsonTok::U64(num);
521                        return Ok(());
522                    } else {
523                        return Err(self.err_parse("number"));
524                    }
525                }
526            }
527            'a'..='z' | 'A'..='Z' | '_' => {
528                self.identbuf.truncate(0);
529                while self.cur >= 'a' && self.cur <= 'z'
530                    || self.cur >= 'A' && self.cur <= 'Z'
531                    || self.cur == '_'
532                {
533                    self.identbuf.push(self.cur);
534                    self.next(i);
535                }
536                if self.identbuf == "true" {
537                    self.tok = DeJsonTok::Bool(true);
538                    return Ok(());
539                }
540                if self.identbuf == "false" {
541                    self.tok = DeJsonTok::Bool(false);
542                    return Ok(());
543                }
544                if self.identbuf == "null" {
545                    self.tok = DeJsonTok::Null;
546                    return Ok(());
547                }
548                self.tok = DeJsonTok::BareIdent;
549                return Err(self.err_token(&format!(
550                    "Got ##{}## needed true, false, null",
551                    self.identbuf
552                )));
553            }
554            '"' => {
555                self.strbuf.truncate(0);
556                self.next(i);
557                while self.cur != '"' {
558                    if self.cur == '\\' {
559                        self.next(i);
560                        match self.cur {
561                            'n' => self.strbuf.push('\n'),
562                            'r' => self.strbuf.push('\r'),
563                            't' => self.strbuf.push('\t'),
564                            'b' => self.strbuf.push('\x08'),
565                            'f' => self.strbuf.push('\x0c'),
566                            '0' => self.strbuf.push('\0'),
567                            '\0' => {
568                                return Err(self.err_parse("string"));
569                            }
570                            'u' => {
571                                if let Some(c) = self.hex_unescape_char(i) {
572                                    self.strbuf.push(c);
573                                    continue;
574                                } else {
575                                    return Err(self.err_parse("string"));
576                                }
577                            }
578                            _ => self.strbuf.push(self.cur),
579                        }
580                        self.next(i);
581                    } else {
582                        if self.cur == '\0' {
583                            return Err(self.err_parse("string"));
584                        }
585                        self.strbuf.push(self.cur);
586                        self.next(i);
587                    }
588                }
589                self.next(i);
590                self.tok = DeJsonTok::Str;
591                return Ok(());
592            }
593            _ => {
594                return Err(self.err_token("tokenizer"));
595            }
596        }
597    }
598
599    /// Helper for reading `\uXXXX` escapes out of a string, properly handing
600    /// surrogate pairs (by potentially unescaping a second `\uXXXX` sequence if
601    /// it would complete a surrogate pair).
602    ///
603    /// On illegal escapes or unpaired surrogates returns None (and caller
604    /// should emit an error).
605    fn hex_unescape_char(&mut self, i: &mut Chars) -> Option<char> {
606        self.next(i);
607        let a = xdigit4(self, i)?;
608        if let Some(c) = core::char::from_u32(a as u32) {
609            return Some(c);
610        }
611        // `a` isn't a valid scalar, but if it's leading surrogate, we look for
612        // a trailing surrogate in a `\uXXXX` sequence immediately after.
613        let a_is_lead = (0xd800..0xdc00).contains(&a);
614        if a_is_lead && self.cur == '\\' {
615            self.next(i);
616            if self.cur == 'u' {
617                self.next(i);
618                let b = xdigit4(self, i)?;
619                let b_is_trail = (0xdc00..0xe000).contains(&b);
620                if b_is_trail {
621                    // It's a valid pair! We have `[a, b]` where `a` is a leading
622                    // surrogate and `b` is a trailing one.
623                    let scalar = (((a as u32 - 0xd800) << 10) | (b as u32 - 0xdc00)) + 0x10000;
624                    // All valid surrogate pairs decode to unicode scalar values
625                    // (e.g. `char`), so this block should always return `Some`, the
626                    // debug_assert exists just to ensure our testing is thorough
627                    // enough.
628                    let ch = core::char::from_u32(scalar);
629                    debug_assert!(ch.is_some());
630                    return ch;
631                }
632            }
633        }
634        return None;
635
636        // Helper to turn next 4 ascii hex digits into a u16
637        fn xdigit4(de: &mut DeJsonState, i: &mut Chars) -> Option<u16> {
638            // as tempting as it is to try to find a way to use from_str_radix on the
639            // next 4 bytes from `i`, we'd still need to do validation to detect cases
640            // like `\u+123` and such which makes it less attractive.
641            (0..4).try_fold(0u16, |acc, _| {
642                let n = match de.cur {
643                    '0'..='9' => de.cur as u16 - '0' as u16,
644                    'a'..='f' => de.cur as u16 - 'a' as u16 + 10,
645                    'A'..='F' => de.cur as u16 - 'A' as u16 + 10,
646                    _ => return None,
647                };
648                de.next(i);
649                Some(acc * 16 + n)
650            })
651        }
652    }
653}
654
655macro_rules! impl_ser_de_json_unsigned {
656    ( $ ty: ident, $ max: expr) => {
657        impl SerJson for $ty {
658            fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
659                s.out.push_str(&self.to_string());
660            }
661        }
662
663        impl DeJson for $ty {
664            fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<$ty, DeJsonErr> {
665                let val = s.u64_range($max as u64)?;
666                s.next_tok(i)?;
667                return Ok(val as $ty);
668            }
669        }
670    };
671}
672
673macro_rules! impl_ser_de_json_signed {
674    ( $ ty: ident, $ min: expr, $ max: expr) => {
675        impl SerJson for $ty {
676            fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
677                s.out.push_str(&self.to_string());
678            }
679        }
680
681        impl DeJson for $ty {
682            fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<$ty, DeJsonErr> {
683                //s.is_prefix(p, i) ?;
684                let val = s.i64_range($min as i64, $max as i64)?;
685                s.next_tok(i)?;
686                return Ok(val as $ty);
687            }
688        }
689    };
690}
691
692macro_rules! impl_ser_de_json_float {
693    ( $ ty: ident) => {
694        impl SerJson for $ty {
695            fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
696                s.out.push_str(&self.to_string());
697            }
698        }
699
700        impl DeJson for $ty {
701            fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<$ty, DeJsonErr> {
702                //s.is_prefix(p, i) ?;
703                let val = s.as_f64()?;
704                s.next_tok(i)?;
705                return Ok(val as $ty);
706            }
707        }
708    };
709}
710
711impl_ser_de_json_unsigned!(usize, core::u64::MAX);
712impl_ser_de_json_unsigned!(u64, core::u64::MAX);
713impl_ser_de_json_unsigned!(u32, core::u32::MAX);
714impl_ser_de_json_unsigned!(u16, core::u16::MAX);
715impl_ser_de_json_unsigned!(u8, core::u8::MAX);
716impl_ser_de_json_signed!(i64, core::i64::MIN, core::i64::MAX);
717impl_ser_de_json_signed!(i32, core::i32::MIN, core::i32::MAX);
718impl_ser_de_json_signed!(i16, core::i16::MIN, core::i16::MAX);
719impl_ser_de_json_signed!(i8, core::i8::MIN, core::i8::MAX);
720impl_ser_de_json_float!(f64);
721impl_ser_de_json_float!(f32);
722
723impl<T> SerJson for Option<T>
724where
725    T: SerJson,
726{
727    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
728        if let Some(v) = self {
729            v.ser_json(d, s);
730        } else {
731            s.out.push_str("null");
732        }
733    }
734}
735
736impl<T> DeJson for Option<T>
737where
738    T: DeJson,
739{
740    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<Self, DeJsonErr> {
741        if let DeJsonTok::Null = s.tok {
742            s.next_tok(i)?;
743            return Ok(None);
744        }
745        Ok(Some(DeJson::de_json(s, i)?))
746    }
747}
748
749impl SerJson for () {
750    fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
751        s.out.push_str("null")
752    }
753}
754
755impl DeJson for () {
756    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<(), DeJsonErr> {
757        if let DeJsonTok::Null = s.tok {
758            s.next_tok(i)?;
759            Ok(())
760        } else {
761            Err(s.err_token("null"))
762        }
763    }
764}
765
766impl SerJson for bool {
767    fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
768        if *self {
769            s.out.push_str("true")
770        } else {
771            s.out.push_str("false")
772        }
773    }
774}
775
776impl DeJson for bool {
777    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<bool, DeJsonErr> {
778        let val = s.as_bool()?;
779        s.next_tok(i)?;
780        Ok(val)
781    }
782}
783
784macro_rules! impl_ser_json_string {
785    ($ty: ident) => {
786        impl SerJson for $ty {
787            fn ser_json(&self, _d: usize, s: &mut SerJsonState) {
788                s.out.push('"');
789                for c in self.chars() {
790                    match c {
791                        '\x08' => s.out += "\\b",
792                        '\x0C' => s.out += "\\f",
793                        '\n' => s.out += "\\n",
794                        '\r' => s.out += "\\r",
795                        '\t' => s.out += "\\t",
796                        _ if c.is_ascii_control() => {
797                            use core::fmt::Write as _;
798                            let _ = write!(s.out, "\\u{:04x}", c as u32);
799                        }
800                        '\\' => s.out += "\\\\",
801                        '"' => s.out += "\\\"",
802                        _ => s.out.push(c),
803                    }
804                }
805                s.out.push('"');
806            }
807        }
808    };
809}
810
811impl_ser_json_string!(String);
812impl_ser_json_string!(str);
813
814impl DeJson for String {
815    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<String, DeJsonErr> {
816        let val = s.as_string()?;
817        s.next_tok(i)?;
818        Ok(val)
819    }
820}
821
822impl<T> SerJson for Vec<T>
823where
824    T: SerJson,
825{
826    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
827        s.out.push('[');
828        if self.len() > 0 {
829            let last = self.len() - 1;
830            for (index, item) in self.iter().enumerate() {
831                s.indent(d + 1);
832                item.ser_json(d + 1, s);
833                if index != last {
834                    s.out.push(',');
835                }
836            }
837        }
838        s.out.push(']');
839    }
840}
841
842impl<T> DeJson for Vec<T>
843where
844    T: DeJson,
845{
846    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<Vec<T>, DeJsonErr> {
847        let mut out = Vec::new();
848        s.block_open(i)?;
849
850        while s.tok != DeJsonTok::BlockClose {
851            out.push(DeJson::de_json(s, i)?);
852            s.eat_comma_block(i)?;
853        }
854        s.block_close(i)?;
855        Ok(out)
856    }
857}
858
859impl<T> SerJson for HashSet<T>
860where
861    T: SerJson,
862{
863    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
864        s.out.push('[');
865        if self.len() > 0 {
866            let last = self.len() - 1;
867            for (index, item) in self.iter().enumerate() {
868                s.indent(d + 1);
869                item.ser_json(d + 1, s);
870                if index != last {
871                    s.out.push(',');
872                }
873            }
874        }
875        s.out.push(']');
876    }
877}
878
879impl<T> DeJson for HashSet<T>
880where
881    T: DeJson + Hash + Eq,
882{
883    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<HashSet<T>, DeJsonErr> {
884        let mut out = HashSet::new();
885        s.block_open(i)?;
886
887        while s.tok != DeJsonTok::BlockClose {
888            out.insert(DeJson::de_json(s, i)?);
889            s.eat_comma_block(i)?;
890        }
891        s.block_close(i)?;
892        Ok(out)
893    }
894}
895
896impl<T> SerJson for LinkedList<T>
897where
898    T: SerJson,
899{
900    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
901        s.out.push('[');
902        if self.len() > 0 {
903            let last = self.len() - 1;
904            for (index, item) in self.iter().enumerate() {
905                s.indent(d + 1);
906                item.ser_json(d + 1, s);
907                if index != last {
908                    s.out.push(',');
909                }
910            }
911        }
912        s.out.push(']');
913    }
914}
915
916impl<T> DeJson for LinkedList<T>
917where
918    T: DeJson,
919{
920    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<LinkedList<T>, DeJsonErr> {
921        let mut out = LinkedList::new();
922        s.block_open(i)?;
923
924        while s.tok != DeJsonTok::BlockClose {
925            out.push_back(DeJson::de_json(s, i)?);
926            s.eat_comma_block(i)?;
927        }
928        s.block_close(i)?;
929        Ok(out)
930    }
931}
932
933impl<T> SerJson for BTreeSet<T>
934where
935    T: SerJson,
936{
937    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
938        s.out.push('[');
939        if self.len() > 0 {
940            let last = self.len() - 1;
941            for (index, item) in self.iter().enumerate() {
942                s.indent(d + 1);
943                item.ser_json(d + 1, s);
944                if index != last {
945                    s.out.push(',');
946                }
947            }
948        }
949        s.out.push(']');
950    }
951}
952
953impl<T> DeJson for BTreeSet<T>
954where
955    T: DeJson + Ord,
956{
957    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<BTreeSet<T>, DeJsonErr> {
958        let mut out = BTreeSet::new();
959        s.block_open(i)?;
960
961        while s.tok != DeJsonTok::BlockClose {
962            out.insert(DeJson::de_json(s, i)?);
963            s.eat_comma_block(i)?;
964        }
965        s.block_close(i)?;
966        Ok(out)
967    }
968}
969
970impl<T> SerJson for [T]
971where
972    T: SerJson,
973{
974    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
975        s.out.push('[');
976        let last = self.len() - 1;
977        for (index, item) in self.iter().enumerate() {
978            item.ser_json(d + 1, s);
979            if index != last {
980                s.out.push(',');
981            }
982        }
983        s.out.push(']');
984    }
985}
986
987impl<T, const N: usize> SerJson for [T; N]
988where
989    T: SerJson,
990{
991    #[inline(always)]
992    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
993        self.as_slice().ser_json(d, s)
994    }
995}
996
997impl<T, const N: usize> DeJson for [T; N]
998where
999    T: DeJson,
1000{
1001    fn de_json(o: &mut DeJsonState, d: &mut Chars) -> Result<Self, DeJsonErr> {
1002        use core::mem::MaybeUninit;
1003
1004        // waiting for uninit_array(or for array::try_from_fn) stabilization
1005        // https://github.com/rust-lang/rust/issues/96097
1006        // https://github.com/rust-lang/rust/issues/89379
1007        let mut to: [MaybeUninit<T>; N] =
1008            unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() };
1009        o.block_open(d)?;
1010
1011        for index in 0..N {
1012            to[index] = match DeJson::de_json(o, d).and_then(|ret| {
1013                o.eat_comma_block(d)?;
1014                Ok(ret)
1015            }) {
1016                Ok(v) => MaybeUninit::new(v),
1017                Err(e) => {
1018                    // drop all the MaybeUninit values which we've already
1019                    // successfully deserialized so we don't leak memory.
1020                    // See https://github.com/not-fl3/nanoserde/issues/79
1021                    for (_, to_drop) in (0..index).zip(to) {
1022                        unsafe { to_drop.assume_init() };
1023                    }
1024                    return Err(e);
1025                }
1026            }
1027        }
1028
1029        // waiting for array_assume_init or core::array::map optimizations
1030        // https://github.com/rust-lang/rust/issues/61956
1031        // initializing before block close so that drop will run automatically if err encountered there
1032        let initialized =
1033            unsafe { (*(&to as *const _ as *const MaybeUninit<_>)).assume_init_read() };
1034        o.block_close(d)?;
1035
1036        Ok(initialized)
1037    }
1038}
1039
1040fn de_json_comma_block<T>(s: &mut DeJsonState, i: &mut Chars) -> Result<T, DeJsonErr>
1041where
1042    T: DeJson,
1043{
1044    let t = DeJson::de_json(s, i);
1045    s.eat_comma_block(i)?;
1046    t
1047}
1048
1049impl<A, B> SerJson for (A, B)
1050where
1051    A: SerJson,
1052    B: SerJson,
1053{
1054    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
1055        s.out.push('[');
1056        self.0.ser_json(d, s);
1057        s.out.push(',');
1058        self.1.ser_json(d, s);
1059        s.out.push(']');
1060    }
1061}
1062
1063impl<A, B> DeJson for (A, B)
1064where
1065    A: DeJson,
1066    B: DeJson,
1067{
1068    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<(A, B), DeJsonErr> {
1069        s.block_open(i)?;
1070        let r = (de_json_comma_block(s, i)?, de_json_comma_block(s, i)?);
1071        s.block_close(i)?;
1072        Ok(r)
1073    }
1074}
1075
1076impl<A, B, C> SerJson for (A, B, C)
1077where
1078    A: SerJson,
1079    B: SerJson,
1080    C: SerJson,
1081{
1082    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
1083        s.out.push('[');
1084        self.0.ser_json(d, s);
1085        s.out.push(',');
1086        self.1.ser_json(d, s);
1087        s.out.push(',');
1088        self.2.ser_json(d, s);
1089        s.out.push(']');
1090    }
1091}
1092
1093impl<A, B, C> DeJson for (A, B, C)
1094where
1095    A: DeJson,
1096    B: DeJson,
1097    C: DeJson,
1098{
1099    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<(A, B, C), DeJsonErr> {
1100        s.block_open(i)?;
1101        let r = (
1102            de_json_comma_block(s, i)?,
1103            de_json_comma_block(s, i)?,
1104            de_json_comma_block(s, i)?,
1105        );
1106        s.block_close(i)?;
1107        Ok(r)
1108    }
1109}
1110
1111impl<A, B, C, D> SerJson for (A, B, C, D)
1112where
1113    A: SerJson,
1114    B: SerJson,
1115    C: SerJson,
1116    D: SerJson,
1117{
1118    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
1119        s.out.push('[');
1120        self.0.ser_json(d, s);
1121        s.out.push(',');
1122        self.1.ser_json(d, s);
1123        s.out.push(',');
1124        self.2.ser_json(d, s);
1125        s.out.push(',');
1126        self.3.ser_json(d, s);
1127        s.out.push(']');
1128    }
1129}
1130
1131impl<A, B, C, D> DeJson for (A, B, C, D)
1132where
1133    A: DeJson,
1134    B: DeJson,
1135    C: DeJson,
1136    D: DeJson,
1137{
1138    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<(A, B, C, D), DeJsonErr> {
1139        s.block_open(i)?;
1140        let r = (
1141            de_json_comma_block(s, i)?,
1142            de_json_comma_block(s, i)?,
1143            de_json_comma_block(s, i)?,
1144            de_json_comma_block(s, i)?,
1145        );
1146        s.block_close(i)?;
1147        Ok(r)
1148    }
1149}
1150
1151impl<K, V> SerJson for HashMap<K, V>
1152where
1153    K: SerJson,
1154    V: SerJson,
1155{
1156    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
1157        s.out.push('{');
1158        let len = self.len();
1159        let mut index = 0;
1160        for (k, v) in self {
1161            s.indent(d + 1);
1162            k.ser_json(d + 1, s);
1163            s.out.push(':');
1164            v.ser_json(d + 1, s);
1165            if (index + 1) < len {
1166                s.conl();
1167            }
1168            index += 1;
1169        }
1170        s.indent(d);
1171        s.out.push('}');
1172    }
1173}
1174
1175impl<K, V> DeJson for HashMap<K, V>
1176where
1177    K: DeJson + Eq + Hash,
1178    V: DeJson,
1179{
1180    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<Self, DeJsonErr> {
1181        let mut h = HashMap::new();
1182        s.curly_open(i)?;
1183        while s.tok != DeJsonTok::CurlyClose {
1184            let k = DeJson::de_json(s, i)?;
1185            s.colon(i)?;
1186            let v = DeJson::de_json(s, i)?;
1187            s.eat_comma_curly(i)?;
1188            h.insert(k, v);
1189        }
1190        s.curly_close(i)?;
1191        Ok(h)
1192    }
1193}
1194
1195impl<T> SerJson for Box<T>
1196where
1197    T: SerJson,
1198{
1199    fn ser_json(&self, d: usize, s: &mut SerJsonState) {
1200        (**self).ser_json(d, s)
1201    }
1202}
1203
1204impl<T> DeJson for Box<T>
1205where
1206    T: DeJson,
1207{
1208    fn de_json(s: &mut DeJsonState, i: &mut Chars) -> Result<Box<T>, DeJsonErr> {
1209        Ok(Box::new(DeJson::de_json(s, i)?))
1210    }
1211}