sonic_rs/serde/
de.rs

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
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
//! Deserialize JSON data to a Rust data structure.

// The code is cloned from [serde_json](https://github.com/serde-rs/json) and modified necessary parts.
use std::{marker::PhantomData, mem::ManuallyDrop, ptr::slice_from_raw_parts, sync::Arc};

use serde::{
    de::{self, Expected, Unexpected},
    forward_to_deserialize_any,
};
use sonic_number::ParserNumber;

use crate::{
    error::{
        Error,
        ErrorCode::{self, EofWhileParsing, RecursionLimitExceeded},
        Result,
    },
    parser::{as_str, ParseStatus, ParsedSlice, Parser, Reference},
    reader::{Read, Reader},
    value::{node::Value, shared::Shared},
    JsonInput,
};
const MAX_ALLOWED_DEPTH: u8 = u8::MAX;

//////////////////////////////////////////////////////////////////////////////

/// A structure that deserializes JSON into Rust values.
pub struct Deserializer<R> {
    pub(crate) parser: Parser<R>,
    scratch: Vec<u8>,
    remaining_depth: u8,
    shared: Option<Arc<Shared>>, // the shared allocator for `Value`
}

// some functions only used for struct visitors.
impl<'de, R: Reader<'de>> Deserializer<R> {
    /// Create a new deserializer.
    pub fn new(read: R) -> Self {
        Self {
            parser: Parser::new(read),
            scratch: Vec::new(),
            remaining_depth: MAX_ALLOWED_DEPTH,
            shared: Option::None,
        }
    }

    /// Parse all number as [`crate::RawNumber`].
    ///
    /// # Example
    /// ```
    /// use sonic_rs::{Deserializer, Value};
    /// let json = r#"{"a":1.2345678901234567890123}"#;
    /// let mut de = Deserializer::from_str(json).use_rawnumber();
    /// let value: Value = de.deserialize().unwrap();
    /// let out = sonic_rs::to_string(&value).unwrap();
    /// assert_eq!(json, out);
    /// ```
    pub fn use_rawnumber(mut self) -> Self {
        self.parser.cfg.use_rawnumber = true;
        self
    }

    /// Parse all number as `RawNumber` and record the raw text for all JSON string.
    ///
    /// This will make sure the the serialize of `number` or `string` will retain from the origin
    /// JSON text.
    ///
    /// # Example
    /// ```
    /// use sonic_rs::{Deserializer, Value};
    /// let data = [
    ///     r#"{"a":1.2345678901234567890123}"#,
    ///     r#"{"a":1,"b":"\\u0001"}"#,
    ///     r#"{"a":1,"b":"💎"}"#,
    ///     r#"{"\\u0001":1,"b":"\\u0001"}"#,
    /// ];
    ///
    /// for json in data {
    ///     let mut de = Deserializer::from_str(json).use_raw();
    ///     let value: Value = de.deserialize().unwrap();
    ///     let out = sonic_rs::to_string(&value).unwrap();
    ///     assert_eq!(json, out);
    /// }
    /// ```
    pub fn use_raw(mut self) -> Self {
        self.parser.cfg.use_raw = true;
        self
    }

    /// Allow to parse JSON with invalid UTF-8 and UTF-16 characters. Will replace them with
    /// `\uFFFD` (displayed as �).
    ///
    /// # Example
    /// ```
    /// use sonic_rs::{Deserializer, Value};
    /// let data = [
    ///     &[b'\"', 0xff, b'\"'][..],         // invalid UTF8 char in string
    ///     br#"{"a":"\ud800","b":"\udc00"}"#, // invalid UTF16 surrogate pair
    /// ];
    /// let expect = [r#""�""#, r#"{"a":"�","b":"�"}"#];
    ///
    /// let mut exp = expect.iter();
    /// for json in data {
    ///     let mut de = Deserializer::from_slice(json).utf8_lossy();
    ///     let value: Value = de.deserialize().unwrap();
    ///     let out = sonic_rs::to_string(&value).unwrap();
    ///     assert_eq!(&out, exp.next().unwrap());
    /// }
    /// ```
    pub fn utf8_lossy(mut self) -> Self {
        self.parser.cfg.utf8_lossy = true;
        self
    }

    /// Deserialize a JSON stream to a Rust data structure.
    ///
    /// It can be used repeatedly and we do not check trailing chars after deserilalized.
    ///
    /// # Example
    ///
    /// ```
    /// # use sonic_rs::{prelude::*, Value};
    ///
    /// use sonic_rs::Deserializer;
    ///
    /// let multiple_json = r#"{"a": 123, "b": "foo"} true [1, 2, 3] wrong chars"#;
    ///
    /// let mut deserializer = Deserializer::from_json(multiple_json);
    ///
    /// let val: Value = deserializer.deserialize().unwrap();
    /// assert_eq!(val["a"].as_i64().unwrap(), 123);
    /// assert_eq!(val["b"].as_str().unwrap(), "foo");
    ///
    /// let val: bool = deserializer.deserialize().unwrap();
    /// assert_eq!(val, true);
    ///
    /// let val: Vec<u8> = deserializer.deserialize().unwrap();
    /// assert_eq!(val, &[1, 2, 3]);
    ///
    /// // encounter the wrong chars in json
    /// assert!(deserializer.deserialize::<Value>().is_err());
    /// ```
    pub fn deserialize<T>(&mut self) -> Result<T>
    where
        T: de::Deserialize<'de>,
    {
        de::Deserialize::deserialize(self)
    }

    /// Convert Deserializer to a [`StreamDeserializer`].
    pub fn into_stream<T>(self) -> StreamDeserializer<'de, T, R> {
        StreamDeserializer {
            de: self,
            data: PhantomData,
            lifetime: PhantomData,
            is_ending: false,
        }
    }
}

impl<'de> Deserializer<Read<'de>> {
    /// Create a new deserializer from a json input [`JsonInput`].
    pub fn from_json<I: JsonInput<'de>>(input: I) -> Self {
        Self::new(Read::from(input))
    }

    /// Create a new deserializer from a string.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &'de str) -> Self {
        Self::new(Read::from(s))
    }

    /// Create a new deserializer from a string slice.
    pub fn from_slice(s: &'de [u8]) -> Self {
        Self::new(Read::from(s))
    }
}

/// An iterator that deserializes a json stream into multiple `T` values.
///
/// # Example
///
/// ```
/// use sonic_rs::{prelude::*, Deserializer, Value};
///
/// let multiple_json = r#"{"a": 123, "b": "foo"} true [1, 2, 3] wrong chars"#;
///
/// let mut stream = Deserializer::from_json(multiple_json).into_stream::<Value>();
///
/// let val = stream.next().unwrap().unwrap();
/// assert_eq!(val["a"].as_i64().unwrap(), 123);
/// assert_eq!(val["b"].as_str().unwrap(), "foo");
///
/// let val = stream.next().unwrap().unwrap();
/// assert_eq!(val, true);
///
/// let val = stream.next().unwrap().unwrap();
/// assert_eq!(val, &[1, 2, 3]);
///
/// // encounter the wrong chars in json
/// assert!(stream.next().unwrap().is_err());
/// ```
pub struct StreamDeserializer<'de, T, R> {
    de: Deserializer<R>,
    data: PhantomData<T>,
    lifetime: PhantomData<&'de R>,
    is_ending: bool,
}

impl<'de, T, R> Iterator for StreamDeserializer<'de, T, R>
where
    T: de::Deserialize<'de>,
    R: Reader<'de>,
{
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.is_ending {
            return None;
        }
        let val: Result<T> = self.de.deserialize();
        if val.is_err() {
            self.is_ending = true;
        }
        Some(val)
    }
}

// We only use our own error type; no need for From conversions provided by the
// standard library's try! macro. This reduces lines of LLVM IR by 4%.
macro_rules! tri {
    ($e:expr $(,)?) => {
        match $e {
            Ok(val) => val,
            Err(err) => {
                return Err(err);
            }
        }
    };
}

pub(crate) use tri;

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

impl<'a, 'de, R: Reader<'de>> DepthGuard<'a, R> {
    fn guard(de: &'a mut Deserializer<R>) -> Result<Self> {
        de.remaining_depth -= 1;
        if de.remaining_depth == 0 {
            return Err(de.parser.error(RecursionLimitExceeded));
        }
        Ok(Self { de })
    }
}

impl<'a, R> Drop for DepthGuard<'a, R> {
    fn drop(&mut self) {
        self.de.remaining_depth += 1;
    }
}

fn visit_number<'de, V>(num: &ParserNumber, visitor: V) -> Result<V::Value>
where
    V: de::Visitor<'de>,
{
    match *num {
        ParserNumber::Float(x) => visitor.visit_f64(x),
        ParserNumber::Unsigned(x) => visitor.visit_u64(x),
        ParserNumber::Signed(x) => visitor.visit_i64(x),
    }
}

pub(crate) fn invalid_type_number(num: &ParserNumber, exp: &dyn Expected) -> Error {
    match *num {
        ParserNumber::Float(x) => de::Error::invalid_type(Unexpected::Float(x), exp),
        ParserNumber::Unsigned(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp),
        ParserNumber::Signed(x) => de::Error::invalid_type(Unexpected::Signed(x), exp),
    }
}

macro_rules! impl_deserialize_number {
    ($method:ident) => {
        fn $method<V>(self, visitor: V) -> Result<V::Value>
        where
            V: de::Visitor<'de>,
        {
            self.deserialize_number(visitor)
        }
    };
}

// some functions only used for struct visitors.
impl<'de, R: Reader<'de>> Deserializer<R> {
    pub(crate) fn deserialize_number<V>(&mut self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(EofWhileParsing));
        };

        let value = match peek {
            c @ b'-' | c @ b'0'..=b'9' => visit_number(&tri!(self.parser.parse_number(c)), visitor),
            _ => Err(self.peek_invalid_type(peek, &visitor)),
        };

        // fixed error position if not matched type
        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    #[cold]
    fn peek_invalid_type(&mut self, peek: u8, exp: &dyn Expected) -> Error {
        self.parser.peek_invalid_type(peek, exp)
    }

    fn end_seq(&mut self) -> Result<()> {
        self.parser.parse_array_end()
    }

    fn end_map(&mut self) -> Result<()> {
        match self.parser.skip_space() {
            Some(b'}') => Ok(()),
            Some(b',') => Err(self.parser.error(ErrorCode::TrailingComma)),
            Some(_) => Err(self.parser.error(ErrorCode::ExpectedObjectCommaOrEnd)),
            None => Err(self.parser.error(ErrorCode::EofWhileParsing)),
        }
    }

    fn scan_integer128(&mut self, buf: &mut String) -> Result<()> {
        match self.parser.read.peek() {
            Some(b'0') => {
                buf.push('0');
                self.parser.read.eat(1);
                // There can be only one leading '0'.
                if let Some(ch) = self.parser.read.peek() {
                    if ch.is_ascii_digit() {
                        return Err(self.parser.error(ErrorCode::InvalidNumber));
                    }
                }
                Ok(())
            }
            Some(c) if c.is_ascii_digit() => {
                buf.push(c as char);
                self.parser.read.eat(1);
                while let c @ b'0'..=b'9' = self.parser.read.peek().unwrap_or_default() {
                    self.parser.read.eat(1);
                    buf.push(c as char);
                }
                Ok(())
            }
            _ => Err(self.parser.error(ErrorCode::InvalidNumber)),
        }
    }

    fn deserialize_lazyvalue<V>(&mut self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let (raw, status) = self.parser.skip_one()?;
        if status == ParseStatus::HasEscaped {
            visitor.visit_str(as_str(raw))
        } else {
            visitor.visit_borrowed_str(as_str(raw))
        }
    }

    fn deserialize_value<V>(&mut self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let mut val = Value::new();
        if self.parser.read.index() == 0 {
            // will parse the JSON inplace
            let cfg = self.parser.cfg;
            let json = self.parser.read.as_u8_slice();

            // get n to check trailing characters in later
            let n = if cfg.utf8_lossy && self.parser.read.next_invalid_utf8() != usize::MAX {
                // repr the invalid utf8, not need to care about the invalid UTF8 char in non-string
                // parts, it will cause errors when parsing.
                val.parse_with_padding(String::from_utf8_lossy(json).as_bytes(), cfg)?
            } else {
                val.parse_with_padding(json, cfg)?
            };
            self.parser.read.eat(n);
        } else {
            let shared = unsafe {
                if self.shared.is_none() {
                    self.shared = Some(Arc::new(Shared::default()));
                }
                let shared = self.shared.as_mut().unwrap();
                &mut *(Arc::as_ptr(shared) as *mut _)
            };
            // deserialize some json parts into `Value`, not use padding buffer, avoid the memory
            // copy
            val.parse_without_padding(shared, &mut self.scratch, &mut self.parser)?
        };

        let val = ManuallyDrop::new(val);
        // #Safety
        // the json is validate before parsing json, and we pass the document using visit_bytes
        // here.
        unsafe {
            let binary =
                &*slice_from_raw_parts(&val as *const _ as *const u8, std::mem::size_of::<Value>());
            visitor.visit_bytes(binary)
        }
    }

    // we deserialize json number from string or number types
    fn deserialize_rawnumber<V>(&mut self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let raw = match self.parser.skip_space_peek() {
            Some(c @ b'-' | c @ b'0'..=b'9') => {
                let start = self.parser.read.index();
                self.parser.read.eat(1);
                self.parser.skip_number(c)?;
                let end = self.parser.read.index();
                as_str(self.parser.read.slice_unchecked(start, end))
            }
            Some(b'"') => {
                self.parser.read.eat(1);
                let start = self.parser.read.index();
                match self.parser.read.next() {
                    Some(c @ b'-' | c @ b'0'..=b'9') => {
                        self.parser.skip_number(c)?;
                    }
                    _ => return Err(self.parser.error(ErrorCode::InvalidNumber)),
                }
                let end = self.parser.read.index();
                let raw = as_str(self.parser.read.slice_unchecked(start, end));
                // match the right quote
                if self.parser.read.next() != Some(b'"') {
                    return Err(self.parser.error(ErrorCode::InvalidNumber));
                }
                raw
            }
            _ => return Err(self.parser.error(ErrorCode::InvalidNumber)),
        };

        visitor.visit_borrowed_str(raw)
    }
}

impl<'de, 'a, R: Reader<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
    type Error = Error;
    #[inline]
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(EofWhileParsing));
        };

        let value = match peek {
            b'n' => {
                tri!(self.parser.parse_literal("ull"));
                visitor.visit_unit()
            }
            b't' => {
                tri!(self.parser.parse_literal("rue"));
                visitor.visit_bool(true)
            }
            b'f' => {
                tri!(self.parser.parse_literal("alse"));
                visitor.visit_bool(false)
            }
            c @ b'-' | c @ b'0'..=b'9' => visit_number(&tri!(self.parser.parse_number(c)), visitor),
            b'"' => match tri!(self.parser.parse_str_impl(&mut self.scratch)) {
                Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
                Reference::Copied(s) => visitor.visit_str(s),
            },
            b'[' => {
                let ret = {
                    let _ = DepthGuard::guard(self);
                    visitor.visit_seq(SeqAccess::new(self))
                };
                match (ret, self.end_seq()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            b'{' => {
                let ret = {
                    let _ = DepthGuard::guard(self);
                    visitor.visit_map(MapAccess::new(self))
                };
                match (ret, self.end_map()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => Err(self.parser.error(ErrorCode::InvalidJsonValue)),
        };

        match value {
            Ok(value) => Ok(value),
            // The de::Error impl creates errors with unknown line and column.
            // Fill in the position here by looking at the current index in the
            // input. There is no way to tell whether this should call `error`
            // or `error` so pick the one that seems correct more often.
            // Worst case, the position is off by one character.
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b't' => {
                tri!(self.parser.parse_literal("rue"));
                visitor.visit_bool(true)
            }
            b'f' => {
                tri!(self.parser.parse_literal("alse"));
                visitor.visit_bool(false)
            }
            _ => Err(self.peek_invalid_type(peek, &visitor)),
        };

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    impl_deserialize_number!(deserialize_i8);
    impl_deserialize_number!(deserialize_i16);
    impl_deserialize_number!(deserialize_i32);
    impl_deserialize_number!(deserialize_i64);
    impl_deserialize_number!(deserialize_u8);
    impl_deserialize_number!(deserialize_u16);
    impl_deserialize_number!(deserialize_u32);
    impl_deserialize_number!(deserialize_u64);
    impl_deserialize_number!(deserialize_f32);
    impl_deserialize_number!(deserialize_f64);

    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let mut buf = String::new();
        match self.parser.skip_space_peek() {
            Some(b'-') => {
                buf.push('-');
                self.parser.read.eat(1);
            }
            Some(_) => {}
            None => {
                return Err(self.parser.error(ErrorCode::EofWhileParsing));
            }
        };

        tri!(self.scan_integer128(&mut buf));

        let value = match buf.parse() {
            Ok(int) => visitor.visit_i128(int),
            Err(_) => {
                return Err(self.parser.error(ErrorCode::NumberOutOfRange));
            }
        };

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.parser.skip_space_peek() {
            Some(b'-') => {
                return Err(self.parser.error(ErrorCode::NumberOutOfRange));
            }
            Some(_) => {}
            None => {
                return Err(self.parser.error(ErrorCode::EofWhileParsing));
            }
        }

        let mut buf = String::new();
        tri!(self.scan_integer128(&mut buf));

        let value = match buf.parse() {
            Ok(int) => visitor.visit_u128(int),
            Err(_) => {
                return Err(self.parser.error(ErrorCode::NumberOutOfRange));
            }
        };

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

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

    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b'"' => match tri!(self.parser.parse_str_impl(&mut self.scratch)) {
                Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
                Reference::Copied(s) => visitor.visit_str(s),
            },
            _ => Err(self.peek_invalid_type(peek, &visitor)),
        };

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

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

    /// Parses a JSON string as bytes. Note that this function does not check
    /// whether the bytes represent a valid UTF-8 string.
    ///
    /// Followed as `serde_json`.
    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b'"' => match tri!(self.parser.parse_string_raw(&mut self.scratch)) {
                ParsedSlice::Borrowed { slice: b, buf: _ } => visitor.visit_borrowed_bytes(b),
                ParsedSlice::Copied(b) => visitor.visit_bytes(b),
            },
            b'[' => {
                self.parser.read.backward(1);
                self.deserialize_seq(visitor)
            }
            _ => Err(self.peek_invalid_type(peek, &visitor)),
        };

        // check invalid utf8 with allow space here
        let _ = self.parser.check_invalid_utf8(true)?;
        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    #[inline]
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        self.deserialize_bytes(visitor)
    }

    /// Parses a `null` as a None, and any other values as a `Some(...)`.
    #[inline]
    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.parser.skip_space_peek() {
            Some(b'n') => {
                self.parser.read.eat(1);
                tri!(self.parser.parse_literal("ull"));
                visitor.visit_none()
            }
            _ => visitor.visit_some(self),
        }
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b'n' => {
                tri!(self.parser.parse_literal("ull"));
                visitor.visit_unit()
            }
            _ => Err(self.peek_invalid_type(peek, &visitor)),
        };

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

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

    /// Parses a newtype struct as the underlying value.
    #[inline]
    fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        {
            if name == crate::serde::rawnumber::TOKEN {
                return self.deserialize_rawnumber(visitor);
            } else if name == crate::lazyvalue::TOKEN {
                return self.deserialize_lazyvalue(visitor);
            } else if name == crate::value::de::TOKEN {
                return self.deserialize_value(visitor);
            }
        }

        let _ = name;
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b'[' => {
                let ret = {
                    let _ = DepthGuard::guard(self);
                    visitor.visit_seq(SeqAccess::new(self))
                };
                match (ret, self.end_seq()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => return Err(self.peek_invalid_type(peek, &visitor)),
        };
        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

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

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

    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b'{' => {
                let ret = {
                    let _ = DepthGuard::guard(self);
                    visitor.visit_map(MapAccess::new(self))
                };
                match (ret, self.end_map()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => return Err(self.peek_invalid_type(peek, &visitor)),
        };
        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let Some(peek) = self.parser.skip_space() else {
            return Err(self.parser.error(ErrorCode::EofWhileParsing));
        };

        let value = match peek {
            b'[' => {
                let ret = {
                    let _ = DepthGuard::guard(self);
                    visitor.visit_seq(SeqAccess::new(self))
                };
                match (ret, self.end_seq()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            b'{' => {
                let ret = {
                    let _ = DepthGuard::guard(self);
                    visitor.visit_map(MapAccess::new(self))
                };
                match (ret, self.end_map()) {
                    (Ok(ret), Ok(())) => Ok(ret),
                    (Err(err), _) | (_, Err(err)) => Err(err),
                }
            }
            _ => return Err(self.peek_invalid_type(peek, &visitor)),
        };

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.parser.fix_position(err)),
        }
    }

    /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight
    /// value, a `[..]`, or a `{..}`.
    #[inline]
    fn deserialize_enum<V>(
        self,
        _name: &str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        match self.parser.skip_space_peek() {
            Some(b'{') => {
                self.parser.read.eat(1);
                let value = {
                    let _ = DepthGuard::guard(self);
                    tri!(visitor.visit_enum(VariantAccess::new(self)))
                };

                match self.parser.skip_space() {
                    Some(b'}') => Ok(value),
                    Some(_) => Err(self.parser.error(ErrorCode::InvalidJsonValue)),
                    None => Err(self.parser.error(ErrorCode::EofWhileParsing)),
                }
            }
            Some(b'"') => visitor.visit_enum(UnitVariantAccess::new(self)),
            Some(_) => Err(self.parser.error(ErrorCode::InvalidJsonValue)),
            None => Err(self.parser.error(ErrorCode::EofWhileParsing)),
        }
    }

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

    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        // NOTE: we use faster skip, and will not validate the skipped parts.
        tri!(self.parser.skip_one());
        visitor.visit_unit()
    }
}

struct SeqAccess<'a, R: 'a> {
    de: &'a mut Deserializer<R>,
    first: bool, // first is marked as
}

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

impl<'de, 'a, R: Reader<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> {
    type Error = Error;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
    where
        T: de::DeserializeSeed<'de>,
    {
        match self.de.parser.skip_space_peek() {
            Some(b']') => Ok(None), // we will check the ending brace after `visit_seq`
            Some(b',') if !self.first => {
                self.de.parser.read.eat(1);
                Ok(Some(tri!(seed.deserialize(&mut *self.de))))
            }
            Some(_) => {
                if self.first {
                    self.first = false;
                    Ok(Some(tri!(seed.deserialize(&mut *self.de))))
                } else {
                    self.de.parser.read.eat(1); // makes the error position is correct
                    Err(self.de.parser.error(ErrorCode::ExpectedArrayCommaOrEnd))
                }
            }
            None => Err(self.de.parser.error(ErrorCode::EofWhileParsing)),
        }
    }
}

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

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

impl<'de, 'a, R: Reader<'de> + 'a> de::MapAccess<'de> for MapAccess<'a, R> {
    type Error = Error;

    #[inline(always)]
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
    where
        K: de::DeserializeSeed<'de>,
    {
        let peek = match self.de.parser.skip_space_peek() {
            Some(b'}') => {
                return Ok(None);
            }
            Some(b',') if !self.first => {
                self.de.parser.read.eat(1);
                self.de.parser.skip_space()
            }
            Some(b) => {
                self.de.parser.read.eat(1);
                if self.first {
                    self.first = false;
                    Some(b)
                } else {
                    return Err(self.de.parser.error(ErrorCode::ExpectedObjectCommaOrEnd));
                }
            }
            None => {
                return Err(self.de.parser.error(ErrorCode::EofWhileParsing));
            }
        };

        match peek {
            Some(b'"') => seed.deserialize(MapKey { de: &mut *self.de }).map(Some),
            Some(b'}') => Err(self.de.parser.error(ErrorCode::TrailingComma)),
            Some(_) => Err(self.de.parser.error(ErrorCode::ExpectObjectKeyOrEnd)),
            None => Err(self.de.parser.error(ErrorCode::EofWhileParsing)),
        }
    }

    #[inline(always)]
    fn next_value<V>(&mut self) -> Result<V>
    where
        V: de::Deserialize<'de>,
    {
        use std::marker::PhantomData;
        self.next_value_seed(PhantomData)
    }

    #[inline(always)]
    fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>>
    where
        K: de::Deserialize<'de>,
        V: de::Deserialize<'de>,
    {
        use std::marker::PhantomData;
        self.next_entry_seed(PhantomData, PhantomData)
    }

    #[inline(always)]
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
    where
        V: de::DeserializeSeed<'de>,
    {
        tri!(self.de.parser.parse_object_clo());
        seed.deserialize(&mut *self.de)
    }
}

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

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

impl<'de, 'a, R: Reader<'de> + 'a> de::EnumAccess<'de> for VariantAccess<'a, R> {
    type Error = Error;
    type Variant = Self;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
    where
        V: de::DeserializeSeed<'de>,
    {
        let val = tri!(seed.deserialize(&mut *self.de));
        tri!(self.de.parser.parse_object_clo());
        Ok((val, self))
    }
}

impl<'de, 'a, R: Reader<'de> + 'a> de::VariantAccess<'de> for VariantAccess<'a, R> {
    type Error = Error;

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

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

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

    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        de::Deserializer::deserialize_struct(self.de, "", fields, visitor)
    }
}

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

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

impl<'de, 'a, R: Reader<'de> + 'a> de::EnumAccess<'de> for UnitVariantAccess<'a, R> {
    type Error = Error;
    type Variant = Self;

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

impl<'de, 'a, R: Reader<'de> + 'a> de::VariantAccess<'de> for UnitVariantAccess<'a, R> {
    type Error = Error;

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

    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
    where
        T: de::DeserializeSeed<'de>,
    {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"newtype variant",
        ))
    }

    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"tuple variant",
        ))
    }

    fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"struct variant",
        ))
    }
}

/// Only deserialize from this after peeking a '"' byte! Otherwise it may
/// deserialize invalid JSON successfully./// Only deserialize from this after peeking a '"' byte!
/// Otherwise it may deserialize invalid JSON successfully.
struct MapKey<'a, R: 'a> {
    de: &'a mut Deserializer<R>,
}

macro_rules! deserialize_numeric_key {
    ($method:ident) => {
        fn $method<V>(self, visitor: V) -> Result<V::Value>
        where
            V: de::Visitor<'de>,
        {
            let value = tri!(self.de.deserialize_number(visitor));
            if self.de.parser.read.next() != Some(b'"') {
                return Err(self.de.parser.error(ErrorCode::ExpectedQuote));
            }

            Ok(value)
        }
    };

    ($method:ident, $delegate:ident) => {
        fn $method<V>(self, visitor: V) -> Result<V::Value>
        where
            V: de::Visitor<'de>,
        {
            match self.de.parser.read.peek() {
                Some(b'0'..=b'9' | b'-') => {}
                _ => return Err(self.de.parser.error(ErrorCode::ExpectedNumericKey)),
            }

            let value = tri!(self.de.$delegate(visitor));

            if self.de.parser.read.next() != Some(b'"') {
                return Err(self.de.parser.error(ErrorCode::ExpectedQuote));
            }

            Ok(value)
        }
    };
}

impl<'de, 'a, R> de::Deserializer<'de> for MapKey<'a, R>
where
    R: Reader<'de>,
{
    type Error = Error;

    #[inline]
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        self.de.scratch.clear();
        match tri!(self.de.parser.parse_str_impl(&mut self.de.scratch)) {
            Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
            Reference::Copied(s) => visitor.visit_str(s),
        }
    }

    deserialize_numeric_key!(deserialize_i8);
    deserialize_numeric_key!(deserialize_i16);
    deserialize_numeric_key!(deserialize_i32);
    deserialize_numeric_key!(deserialize_i64);
    deserialize_numeric_key!(deserialize_i128, deserialize_i128);
    deserialize_numeric_key!(deserialize_u8);
    deserialize_numeric_key!(deserialize_u16);
    deserialize_numeric_key!(deserialize_u32);
    deserialize_numeric_key!(deserialize_u64);
    deserialize_numeric_key!(deserialize_u128, deserialize_u128);
    deserialize_numeric_key!(deserialize_f32);
    deserialize_numeric_key!(deserialize_f64);

    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        let mut value = match self.de.parser.read.next() {
            Some(b't') => {
                tri!(self.de.parser.parse_literal("rue"));
                visitor.visit_bool(true)
            }
            Some(b'f') => {
                tri!(self.de.parser.parse_literal("alse"));
                visitor.visit_bool(false)
            }
            None => Err(self.de.parser.error(ErrorCode::EofWhileParsing)),
            Some(peek) => Err(self.de.peek_invalid_type(peek, &visitor)),
        };

        if self.de.parser.read.next() != Some(b'"') {
            value = Err(self.de.parser.error(ErrorCode::ExpectedQuote));
        }

        match value {
            Ok(value) => Ok(value),
            Err(err) => Err(self.de.parser.fix_position(err)),
        }
    }

    #[inline]
    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        // Map keys cannot be null.
        visitor.visit_some(self)
    }

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

    #[inline]
    fn deserialize_enum<V>(
        self,
        name: &'static str,
        variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        self.de.parser.read.backward(1);
        self.de.deserialize_enum(name, variants, visitor)
    }

    #[inline]
    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        self.de.parser.read.backward(1);
        self.de.deserialize_bytes(visitor)
    }

    #[inline]
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
    where
        V: de::Visitor<'de>,
    {
        self.de.parser.read.backward(1);
        self.de.deserialize_bytes(visitor)
    }

    forward_to_deserialize_any! {
        char str string unit unit_struct seq tuple tuple_struct map struct
        identifier ignored_any
    }
}
//////////////////////////////////////////////////////////////////////////////

fn from_trait<'de, R, T>(read: R) -> Result<T>
where
    R: Reader<'de>,
    T: de::Deserialize<'de>,
{
    // check JSON size, because the design of `sonic_rs::Value`, parsing JSON larger than 2 GB is
    // not supported
    let len = read.as_u8_slice().len();
    if len >= (1 << 32) {
        return Err(crate::error::make_error(format!(
            "Only support JSON less than 2 GB, the input JSON is too large here, len is {len}"
        )));
    }

    let mut de = Deserializer::new(read);
    #[cfg(feature = "arbitrary_precision")]
    {
        de = de.use_rawnumber();
    }

    #[cfg(feature = "use_raw")]
    {
        de = de.use_raw();
    }

    #[cfg(feature = "utf8_lossy")]
    {
        de = de.utf8_lossy();
    }

    let value = tri!(de::Deserialize::deserialize(&mut de));

    // Make sure the whole stream has been consumed.
    tri!(de.parser.parse_trailing());

    // check invalid utf8
    tri!(de.parser.read.check_utf8_final());
    Ok(value)
}

/// Deserialize an instance of type `T` from bytes of JSON text.
/// If user can guarantee the JSON is valid UTF-8, recommend to use `from_slice_unchecked` instead.
pub fn from_slice<'a, T>(json: &'a [u8]) -> Result<T>
where
    T: de::Deserialize<'a>,
{
    from_trait(Read::new(json, true))
}

/// Deserialize an instance of type `T` from bytes of JSON text.
///
/// # Safety
/// The json passed in must be valid UTF-8.
pub unsafe fn from_slice_unchecked<'a, T>(json: &'a [u8]) -> Result<T>
where
    T: de::Deserialize<'a>,
{
    from_trait(Read::new(json, false))
}

/// Deserialize an instance of type `T` from a string of JSON text.
pub fn from_str<'a, T>(s: &'a str) -> Result<T>
where
    T: de::Deserialize<'a>,
{
    from_trait(Read::new(s.as_bytes(), false))
}