musli_json/de/
mod.rs

1mod object_decoder;
2use self::object_decoder::JsonObjectDecoder;
3
4mod object_pair_decoder;
5use self::object_pair_decoder::JsonObjectPairDecoder;
6
7mod key_decoder;
8use self::key_decoder::JsonKeyDecoder;
9
10mod key_unsigned_visitor;
11use self::key_unsigned_visitor::KeyUnsignedVisitor;
12
13mod key_signed_visitor;
14use self::key_signed_visitor::KeySignedVisitor;
15
16mod sequence_decoder;
17use self::sequence_decoder::JsonSequenceDecoder;
18
19mod variant_decoder;
20use self::variant_decoder::JsonVariantDecoder;
21
22use core::fmt;
23use core::str;
24
25#[cfg(feature = "alloc")]
26use alloc::vec::Vec;
27
28use musli::de::{
29    Decode, DecodeUnsized, Decoder, NumberVisitor, SequenceDecoder, SizeHint, Skip, ValueVisitor,
30    Visitor,
31};
32use musli::hint::{MapHint, SequenceHint};
33use musli::Context;
34#[cfg(feature = "musli-value")]
35use musli_utils::options;
36#[cfg(feature = "musli-value")]
37use musli_utils::Options;
38
39#[cfg(not(feature = "parse-full"))]
40use crate::parser::integer::{
41    parse_signed_base as parse_signed, parse_unsigned_base as parse_unsigned,
42};
43#[cfg(feature = "parse-full")]
44use crate::parser::integer::{
45    parse_signed_full as parse_signed, parse_unsigned_full as parse_unsigned,
46};
47use crate::parser::{integer, string, Parser, StringReference, Token};
48
49#[cfg(feature = "musli-value")]
50const BUFFER_OPTIONS: Options = options::new().with_map_keys_as_numbers(true).build();
51
52/// A JSON decoder for Müsli.
53pub(crate) struct JsonDecoder<'a, P, C: ?Sized> {
54    cx: &'a C,
55    parser: P,
56}
57
58impl<'a, 'de, P, C> JsonDecoder<'a, P, C>
59where
60    P: Parser<'de>,
61    C: ?Sized + Context,
62{
63    /// Construct a new fixed width message encoder.
64    #[inline]
65    pub(crate) fn new(cx: &'a C, parser: P) -> Self {
66        Self { cx, parser }
67    }
68
69    /// Skip over any values.
70    pub(crate) fn skip_any(mut self) -> Result<(), C::Error> {
71        let start = self.cx.mark();
72        let actual = self.parser.peek(self.cx)?;
73
74        match actual {
75            Token::OpenBrace => self.decode_map(|_| Ok(())),
76            Token::OpenBracket => self.decode_sequence(|_| Ok(())),
77            Token::Null => self.parse_null(),
78            Token::True => self.parse_true(),
79            Token::False => self.parse_false(),
80            Token::Number => integer::skip_number(self.cx, self.parser.borrow_mut()),
81            Token::String => {
82                // Skip over opening quote.
83                self.parser.skip(self.cx, 1)?;
84                string::skip_string(self.cx, self.parser.borrow_mut(), true)
85            }
86            actual => Err(self
87                .cx
88                .marked_message(start, format_args!("Expected value, found {actual}"))),
89        }
90    }
91
92    #[inline]
93    fn parse_true(mut self) -> Result<(), C::Error> {
94        self.parser.parse_exact(self.cx, "true")
95    }
96
97    #[inline]
98    fn parse_false(mut self) -> Result<(), C::Error> {
99        self.parser.parse_exact(self.cx, "false")
100    }
101
102    #[inline]
103    fn parse_null(mut self) -> Result<(), C::Error> {
104        self.parser.parse_exact(self.cx, "null")
105    }
106}
107
108#[musli::decoder]
109impl<'a, 'de, P, C> Decoder<'de> for JsonDecoder<'a, P, C>
110where
111    P: Parser<'de>,
112    C: ?Sized + Context,
113{
114    type Cx = C;
115    type Error = C::Error;
116    type Mode = C::Mode;
117    type WithContext<'this, U> = JsonDecoder<'this, P, U> where U: 'this + Context;
118    #[cfg(feature = "musli-value")]
119    type DecodeBuffer = musli_value::AsValueDecoder<'a, BUFFER_OPTIONS, C>;
120    type DecodePack = JsonSequenceDecoder<'a, P, C>;
121    type DecodeSequence = JsonSequenceDecoder<'a, P, C>;
122    type DecodeSequenceHint = JsonSequenceDecoder<'a, P, C>;
123    type DecodeMap = JsonObjectDecoder<'a, P, C>;
124    type DecodeMapHint = JsonObjectDecoder<'a, P, C>;
125    type DecodeMapEntries = JsonObjectDecoder<'a, P, C>;
126    type DecodeSome = JsonDecoder<'a, P, C>;
127    type DecodeVariant = JsonVariantDecoder<'a, P, C>;
128
129    #[inline]
130    fn cx(&self) -> &Self::Cx {
131        self.cx
132    }
133
134    #[inline]
135    fn with_context<U>(self, cx: &U) -> Result<Self::WithContext<'_, U>, C::Error>
136    where
137        U: Context,
138    {
139        Ok(JsonDecoder::new(cx, self.parser))
140    }
141
142    #[inline]
143    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        write!(f, "value that can be decoded from JSON")
145    }
146
147    #[inline]
148    fn decode<T>(self) -> Result<T, Self::Error>
149    where
150        T: Decode<'de, Self::Mode>,
151    {
152        self.cx.decode(self)
153    }
154
155    #[inline]
156    fn decode_unsized<T, F, O>(self, f: F) -> Result<O, Self::Error>
157    where
158        T: ?Sized + DecodeUnsized<'de, Self::Mode>,
159        F: FnOnce(&T) -> Result<O, Self::Error>,
160    {
161        self.cx.decode_unsized(self, f)
162    }
163
164    #[inline]
165    fn skip(self) -> Result<(), C::Error> {
166        self.skip_any()
167    }
168
169    #[inline]
170    fn try_skip(self) -> Result<Skip, C::Error> {
171        self.skip()?;
172        Ok(Skip::Skipped)
173    }
174
175    #[cfg(feature = "musli-value")]
176    #[inline]
177    fn decode_buffer(self) -> Result<Self::DecodeBuffer, C::Error> {
178        let cx = self.cx;
179        let value = self.decode::<musli_value::Value>()?;
180        // JSON: Encodes numbers in objects as strings, so we need to permit
181        // treating them as such here as well.
182        Ok(value.into_value_decoder(cx))
183    }
184
185    #[inline]
186    fn decode_unit(self) -> Result<(), C::Error> {
187        self.skip()
188    }
189
190    #[inline]
191    fn decode_bool(mut self) -> Result<bool, C::Error> {
192        match self.parser.peek(self.cx)? {
193            Token::True => {
194                self.parse_true()?;
195                Ok(true)
196            }
197            Token::False => {
198                self.parse_false()?;
199                Ok(false)
200            }
201            actual => Err(self
202                .cx
203                .message(format_args!("Expected boolean, was {actual}"))),
204        }
205    }
206
207    #[inline]
208    fn decode_char(mut self) -> Result<char, C::Error> {
209        let start = self.cx.mark();
210
211        let Some(mut scratch) = self.cx.alloc() else {
212            return Err(self.cx.message("Failed to allocate scratch buffer"));
213        };
214
215        let string = match self.parser.parse_string(self.cx, true, &mut scratch)? {
216            StringReference::Borrowed(string) => string,
217            StringReference::Scratch(string) => string,
218        };
219
220        let mut it = string.chars();
221        let first = it.next();
222
223        match (first, it.next()) {
224            (Some(c), None) => Ok(c),
225            _ => Err(self
226                .cx
227                .marked_message(start, "Expected string with a single character")),
228        }
229    }
230
231    #[inline]
232    fn decode_u8(mut self) -> Result<u8, C::Error> {
233        parse_unsigned(self.cx, self.parser.borrow_mut())
234    }
235
236    #[inline]
237    fn decode_u16(mut self) -> Result<u16, C::Error> {
238        parse_unsigned(self.cx, self.parser.borrow_mut())
239    }
240
241    #[inline]
242    fn decode_u32(mut self) -> Result<u32, C::Error> {
243        parse_unsigned(self.cx, self.parser.borrow_mut())
244    }
245
246    #[inline]
247    fn decode_u64(mut self) -> Result<u64, C::Error> {
248        parse_unsigned(self.cx, self.parser.borrow_mut())
249    }
250
251    #[inline]
252    fn decode_u128(mut self) -> Result<u128, C::Error> {
253        parse_unsigned(self.cx, self.parser.borrow_mut())
254    }
255
256    #[inline]
257    fn decode_i8(mut self) -> Result<i8, C::Error> {
258        parse_signed(self.cx, self.parser.borrow_mut())
259    }
260
261    #[inline]
262    fn decode_i16(mut self) -> Result<i16, C::Error> {
263        parse_signed(self.cx, self.parser.borrow_mut())
264    }
265
266    #[inline]
267    fn decode_i32(mut self) -> Result<i32, C::Error> {
268        parse_signed(self.cx, self.parser.borrow_mut())
269    }
270
271    #[inline]
272    fn decode_i64(mut self) -> Result<i64, C::Error> {
273        parse_signed(self.cx, self.parser.borrow_mut())
274    }
275
276    #[inline]
277    fn decode_i128(mut self) -> Result<i128, C::Error> {
278        parse_signed(self.cx, self.parser.borrow_mut())
279    }
280
281    #[inline]
282    fn decode_usize(mut self) -> Result<usize, C::Error> {
283        parse_unsigned(self.cx, self.parser.borrow_mut())
284    }
285
286    #[inline]
287    fn decode_isize(mut self) -> Result<isize, C::Error> {
288        parse_signed(self.cx, self.parser.borrow_mut())
289    }
290
291    #[inline]
292    fn decode_f32(mut self) -> Result<f32, C::Error> {
293        self.parser.parse_f32(self.cx)
294    }
295
296    #[inline]
297    fn decode_f64(mut self) -> Result<f64, C::Error> {
298        self.parser.parse_f64(self.cx)
299    }
300
301    #[inline]
302    fn decode_array<const N: usize>(self) -> Result<[u8; N], C::Error> {
303        let cx = self.cx;
304        let mark = cx.mark();
305
306        self.decode_sequence(|seq| {
307            let mut bytes = [0; N];
308            let mut index = 0;
309
310            while let Some(item) = seq.try_decode_next()? {
311                if index <= N {
312                    bytes[index] = item.decode_u8()?;
313                }
314
315                index += 1;
316            }
317
318            if index != N {
319                return Err(cx.marked_message(
320                    mark,
321                    format_args!(
322                        "Array with length {index} does not have the expected {N} number of elements"
323                    ),
324                ));
325            }
326
327            Ok(bytes)
328        })
329    }
330
331    #[inline]
332    fn decode_number<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
333    where
334        V: NumberVisitor<'de, C>,
335    {
336        self.parser.parse_number(self.cx, visitor)
337    }
338
339    #[cfg(feature = "alloc")]
340    #[inline]
341    fn decode_bytes<V>(self, visitor: V) -> Result<V::Ok, C::Error>
342    where
343        V: ValueVisitor<'de, C, [u8]>,
344    {
345        let cx = self.cx;
346
347        self.decode_sequence(|seq| {
348            let mut bytes = Vec::with_capacity(seq.size_hint().or_default());
349
350            while let Some(item) = seq.try_decode_next()? {
351                bytes.push(item.decode_u8()?);
352            }
353
354            visitor.visit_owned(cx, bytes)
355        })
356    }
357
358    #[inline]
359    fn decode_string<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
360    where
361        V: ValueVisitor<'de, C, str>,
362    {
363        let Some(mut scratch) = self.cx.alloc() else {
364            return Err(self.cx.message("Failed to allocate scratch buffer"));
365        };
366
367        match self.parser.parse_string(self.cx, true, &mut scratch)? {
368            StringReference::Borrowed(borrowed) => visitor.visit_borrowed(self.cx, borrowed),
369            StringReference::Scratch(string) => visitor.visit_ref(self.cx, string),
370        }
371    }
372
373    #[inline]
374    fn decode_option(mut self) -> Result<Option<Self::DecodeSome>, C::Error> {
375        if self.parser.peek(self.cx)?.is_null() {
376            self.parse_null()?;
377            Ok(None)
378        } else {
379            Ok(Some(self))
380        }
381    }
382
383    #[inline]
384    fn decode_pack<F, O>(self, f: F) -> Result<O, C::Error>
385    where
386        F: FnOnce(&mut Self::DecodePack) -> Result<O, C::Error>,
387    {
388        let mut decoder = JsonSequenceDecoder::new(self.cx, None, self.parser)?;
389        let output = f(&mut decoder)?;
390        decoder.skip_sequence_remaining()?;
391        Ok(output)
392    }
393
394    #[inline]
395    fn decode_sequence<F, O>(self, f: F) -> Result<O, C::Error>
396    where
397        F: FnOnce(&mut Self::DecodeSequence) -> Result<O, C::Error>,
398    {
399        let mut decoder = JsonSequenceDecoder::new(self.cx, None, self.parser)?;
400        let output = f(&mut decoder)?;
401        decoder.skip_sequence_remaining()?;
402        Ok(output)
403    }
404
405    #[inline]
406    fn decode_sequence_hint<F, O>(self, hint: &SequenceHint, f: F) -> Result<O, C::Error>
407    where
408        F: FnOnce(&mut Self::DecodeSequenceHint) -> Result<O, C::Error>,
409    {
410        let mut decoder = JsonSequenceDecoder::new(self.cx, Some(hint.size), self.parser)?;
411        let output = f(&mut decoder)?;
412        decoder.skip_sequence_remaining()?;
413        Ok(output)
414    }
415
416    #[inline]
417    fn decode_map<F, O>(self, f: F) -> Result<O, C::Error>
418    where
419        F: FnOnce(&mut Self::DecodeMap) -> Result<O, C::Error>,
420    {
421        let mut decoder = JsonObjectDecoder::new(self.cx, None, self.parser)?;
422        let output = f(&mut decoder)?;
423        decoder.skip_object_remaining()?;
424        Ok(output)
425    }
426
427    #[inline]
428    fn decode_map_hint<F, O>(self, hint: &MapHint, f: F) -> Result<O, C::Error>
429    where
430        F: FnOnce(&mut Self::DecodeMapHint) -> Result<O, C::Error>,
431    {
432        let mut decoder = JsonObjectDecoder::new(self.cx, Some(hint.size), self.parser)?;
433        let output = f(&mut decoder)?;
434        decoder.skip_object_remaining()?;
435        Ok(output)
436    }
437
438    #[inline]
439    fn decode_map_entries(self) -> Result<Self::DecodeMapEntries, C::Error> {
440        JsonObjectDecoder::new(self.cx, None, self.parser)
441    }
442
443    #[inline]
444    fn decode_variant<F, O>(self, f: F) -> Result<O, C::Error>
445    where
446        F: FnOnce(&mut Self::DecodeVariant) -> Result<O, C::Error>,
447    {
448        let mut decoder = JsonVariantDecoder::new(self.cx, self.parser)?;
449        let output = f(&mut decoder)?;
450        decoder.end()?;
451        Ok(output)
452    }
453
454    #[inline]
455    fn decode_any<V>(mut self, visitor: V) -> Result<V::Ok, C::Error>
456    where
457        V: Visitor<'de, C>,
458    {
459        let cx = self.cx;
460
461        match self.parser.peek(cx)? {
462            Token::OpenBrace => self.decode_map(|decoder| visitor.visit_map(cx, decoder)),
463            Token::OpenBracket => {
464                self.decode_sequence(|decoder| visitor.visit_sequence(cx, decoder))
465            }
466            Token::String => {
467                let visitor = visitor.visit_string(cx, SizeHint::Any)?;
468                self.decode_string(visitor)
469            }
470            Token::Number => {
471                let visitor = visitor.visit_number(cx)?;
472                self.decode_number(visitor)
473            }
474            Token::Null => {
475                self.parse_null()?;
476                visitor.visit_unit(cx)
477            }
478            Token::True => {
479                self.parse_true()?;
480                visitor.visit_bool(cx, true)
481            }
482            Token::False => {
483                self.parse_false()?;
484                visitor.visit_bool(cx, false)
485            }
486            token => Err(cx.message(format_args!("Expected value, found {token:?}"))),
487        }
488    }
489}