musli_value/
de.rs

1use core::fmt;
2use core::slice;
3
4#[cfg(feature = "alloc")]
5use musli::de::ValueVisitor;
6use musli::de::{
7    AsDecoder, Decode, DecodeUnsized, Decoder, EntriesDecoder, EntryDecoder, MapDecoder,
8    SequenceDecoder, SizeHint, Skip, VariantDecoder, Visitor,
9};
10#[cfg(feature = "alloc")]
11use musli::hint::{MapHint, SequenceHint};
12use musli::Context;
13use musli_storage::de::StorageDecoder;
14use musli_utils::reader::SliceReader;
15use musli_utils::Options;
16
17use crate::error::ErrorMessage;
18use crate::type_hint::{NumberHint, TypeHint};
19use crate::value::{Number, Value};
20use crate::AsValueDecoder;
21
22/// Encoder for a single value.
23pub struct ValueDecoder<'a, 'de, const OPT: Options, C: ?Sized> {
24    cx: &'a C,
25    value: &'de Value,
26    #[cfg(feature = "alloc")]
27    map_key: bool,
28}
29
30impl<'a, 'de, const OPT: Options, C: ?Sized> ValueDecoder<'a, 'de, OPT, C> {
31    #[inline]
32    pub(crate) const fn new(cx: &'a C, value: &'de Value) -> Self {
33        Self {
34            cx,
35            value,
36            #[cfg(feature = "alloc")]
37            map_key: false,
38        }
39    }
40
41    #[inline]
42    pub(crate) const fn with_map_key(cx: &'a C, value: &'de Value) -> Self {
43        Self {
44            cx,
45            value,
46            #[cfg(feature = "alloc")]
47            map_key: true,
48        }
49    }
50}
51
52macro_rules! ensure_number {
53    ($self:expr, $opt:expr, $hint:ident, $ident:ident $tt:tt, Value::$variant:ident($block:ident) => $ty:ty) => {
54        match $self.value {
55            Value::$variant($block) => <$ty>::from_number($block).map_err($self.cx.map_message()),
56            #[cfg(feature = "alloc")]
57            Value::String(string) if musli_utils::options::is_map_keys_as_numbers::<$opt>() && $self.map_key => {
58                match <$ty>::parse_number(string) {
59                    Some(value) => Ok(value),
60                    None => Err($self.cx.message(ErrorMessage::ExpectedStringAsNumber)),
61                }
62            }
63            value => {
64                let $hint = value.type_hint();
65                return Err($self.cx.message(ErrorMessage::$ident $tt));
66            }
67        }
68    };
69}
70
71macro_rules! ensure {
72    ($self:expr, $hint:ident, $ident:ident $tt:tt, $pat:pat => $block:expr) => {
73        match $self.value {
74            $pat => $block,
75            value => {
76                let $hint = value.type_hint();
77                return Err($self.cx.message(ErrorMessage::$ident $tt));
78            }
79        }
80    };
81}
82
83#[musli::decoder]
84impl<'a, 'de, C: ?Sized + Context, const OPT: Options> Decoder<'de>
85    for ValueDecoder<'a, 'de, OPT, C>
86{
87    type Cx = C;
88    type Error = C::Error;
89    type Mode = C::Mode;
90    type WithContext<'this, U> = ValueDecoder<'this, 'de, OPT, U> where U: 'this + Context;
91    type DecodeBuffer = AsValueDecoder<'a, OPT, C>;
92    type DecodeSome = Self;
93    type DecodePack = StorageDecoder<'a, SliceReader<'de>, OPT, C>;
94    type DecodeSequence = IterValueDecoder<'a, 'de, OPT, C>;
95    type DecodeSequenceHint = IterValueDecoder<'a, 'de, OPT, C>;
96    type DecodeMap = IterValuePairsDecoder<'a, 'de, OPT, C>;
97    type DecodeMapHint = IterValuePairsDecoder<'a, 'de, OPT, C>;
98    type DecodeMapEntries = IterValuePairsDecoder<'a, 'de, OPT, C>;
99    type DecodeVariant = IterValueVariantDecoder<'a, 'de, OPT, C>;
100
101    #[inline]
102    fn cx(&self) -> &Self::Cx {
103        self.cx
104    }
105
106    #[inline]
107    fn with_context<U>(self, cx: &U) -> Result<Self::WithContext<'_, U>, C::Error>
108    where
109        U: Context,
110    {
111        Ok(ValueDecoder::new(cx, self.value))
112    }
113
114    #[inline]
115    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(f, "cannot be decoded from value")
117    }
118
119    #[inline]
120    fn decode<T>(self) -> Result<T, C::Error>
121    where
122        T: Decode<'de, Self::Mode>,
123    {
124        self.cx.decode(self)
125    }
126
127    #[inline]
128    fn decode_unsized<T, F, O>(self, f: F) -> Result<O, Self::Error>
129    where
130        T: ?Sized + DecodeUnsized<'de, Self::Mode>,
131        F: FnOnce(&T) -> Result<O, Self::Error>,
132    {
133        self.cx.decode_unsized(self, f)
134    }
135
136    #[inline]
137    fn skip(self) -> Result<(), C::Error> {
138        Ok(())
139    }
140
141    #[inline]
142    fn try_skip(self) -> Result<Skip, C::Error> {
143        Ok(Skip::Skipped)
144    }
145
146    #[inline]
147    fn decode_buffer(self) -> Result<Self::DecodeBuffer, C::Error> {
148        Ok(AsValueDecoder::new(self.cx, self.value.clone()))
149    }
150
151    #[inline]
152    fn decode_unit(self) -> Result<(), C::Error> {
153        ensure!(self, hint, ExpectedUnit(hint), Value::Unit => Ok(()))
154    }
155
156    #[inline]
157    fn decode_bool(self) -> Result<bool, C::Error> {
158        ensure!(self, hint, ExpectedBool(hint), Value::Bool(b) => Ok(*b))
159    }
160
161    #[inline]
162    fn decode_char(self) -> Result<char, C::Error> {
163        ensure!(self, hint, ExpectedChar(hint), Value::Char(c) => Ok(*c))
164    }
165
166    #[inline]
167    fn decode_u8(self) -> Result<u8, C::Error> {
168        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::U8, hint), Value::Number(n) => u8)
169    }
170
171    #[inline]
172    fn decode_u16(self) -> Result<u16, C::Error> {
173        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::U16, hint), Value::Number(n) => u16)
174    }
175
176    #[inline]
177    fn decode_u32(self) -> Result<u32, C::Error> {
178        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::U32, hint), Value::Number(n) => u32)
179    }
180
181    #[inline]
182    fn decode_u64(self) -> Result<u64, C::Error> {
183        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::U64, hint), Value::Number(n) => u64)
184    }
185
186    #[inline]
187    fn decode_u128(self) -> Result<u128, C::Error> {
188        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::U128, hint), Value::Number(n) => u128)
189    }
190
191    #[inline]
192    fn decode_i8(self) -> Result<i8, C::Error> {
193        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::I8, hint), Value::Number(n) => i8)
194    }
195
196    #[inline]
197    fn decode_i16(self) -> Result<i16, C::Error> {
198        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::I16, hint), Value::Number(n) => i16)
199    }
200
201    #[inline]
202    fn decode_i32(self) -> Result<i32, C::Error> {
203        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::I32, hint), Value::Number(n) => i32)
204    }
205
206    #[inline]
207    fn decode_i64(self) -> Result<i64, C::Error> {
208        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::I64, hint), Value::Number(n) => i64)
209    }
210
211    #[inline]
212    fn decode_i128(self) -> Result<i128, C::Error> {
213        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::I128, hint), Value::Number(n) => i128)
214    }
215
216    #[inline]
217    fn decode_usize(self) -> Result<usize, C::Error> {
218        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::Usize, hint), Value::Number(n) => usize)
219    }
220
221    #[inline]
222    fn decode_isize(self) -> Result<isize, C::Error> {
223        ensure_number!(self, OPT, hint, ExpectedNumber(NumberHint::Isize, hint), Value::Number(n) => isize)
224    }
225
226    #[inline]
227    fn decode_f32(self) -> Result<f32, C::Error> {
228        ensure!(self, hint, ExpectedNumber(NumberHint::F32, hint), Value::Number(Number::F32(n)) => Ok(*n))
229    }
230
231    #[inline]
232    fn decode_f64(self) -> Result<f64, C::Error> {
233        ensure!(self, hint, ExpectedNumber(NumberHint::F64, hint), Value::Number(Number::F64(n)) => Ok(*n))
234    }
235
236    #[cfg(feature = "alloc")]
237    #[inline]
238    fn decode_array<const N: usize>(self) -> Result<[u8; N], C::Error> {
239        ensure!(self, hint, ExpectedBytes(hint), Value::Bytes(bytes) => {
240            <[u8; N]>::try_from(bytes.as_slice()).map_err(|_| self.cx.message(ErrorMessage::ArrayOutOfBounds))
241        })
242    }
243
244    #[cfg(feature = "alloc")]
245    #[inline]
246    fn decode_bytes<V>(self, visitor: V) -> Result<V::Ok, C::Error>
247    where
248        V: ValueVisitor<'de, C, [u8]>,
249    {
250        ensure!(self, hint, ExpectedBytes(hint), Value::Bytes(bytes) => {
251            visitor.visit_borrowed(self.cx, bytes)
252        })
253    }
254
255    #[cfg(feature = "alloc")]
256    #[inline]
257    fn decode_string<V>(self, visitor: V) -> Result<V::Ok, C::Error>
258    where
259        V: ValueVisitor<'de, C, str>,
260    {
261        ensure!(self, hint, ExpectedString(hint), Value::String(string) => {
262            visitor.visit_borrowed(self.cx, string)
263        })
264    }
265
266    #[cfg(feature = "alloc")]
267    #[inline]
268    fn decode_option(self) -> Result<Option<Self::DecodeSome>, C::Error> {
269        ensure!(self, hint, ExpectedOption(hint), Value::Option(option) => {
270            Ok(option.as_ref().map(|some| ValueDecoder::new(self.cx, some)))
271        })
272    }
273
274    #[cfg(feature = "alloc")]
275    #[inline]
276    fn decode_pack<F, O>(self, f: F) -> Result<O, C::Error>
277    where
278        F: FnOnce(&mut Self::DecodePack) -> Result<O, C::Error>,
279    {
280        ensure!(self, hint, ExpectedPack(hint), Value::Bytes(pack) => {
281            f(&mut StorageDecoder::new(self.cx, SliceReader::new(pack)))
282        })
283    }
284
285    #[cfg(feature = "alloc")]
286    #[inline]
287    fn decode_sequence<F, O>(self, f: F) -> Result<O, <Self::Cx as Context>::Error>
288    where
289        F: FnOnce(&mut Self::DecodeSequence) -> Result<O, <Self::Cx as Context>::Error>,
290    {
291        ensure!(self, hint, ExpectedSequence(hint), Value::Sequence(sequence) => {
292            f(&mut IterValueDecoder::new(self.cx, sequence))
293        })
294    }
295
296    #[cfg(feature = "alloc")]
297    #[inline]
298    fn decode_sequence_hint<F, O>(self, _: &SequenceHint, f: F) -> Result<O, C::Error>
299    where
300        F: FnOnce(&mut Self::DecodeSequenceHint) -> Result<O, C::Error>,
301    {
302        ensure!(self, hint, ExpectedSequence(hint), Value::Sequence(sequence) => {
303            f(&mut IterValueDecoder::new(self.cx, sequence))
304        })
305    }
306
307    #[cfg(feature = "alloc")]
308    #[inline]
309    fn decode_map<F, O>(self, f: F) -> Result<O, C::Error>
310    where
311        F: FnOnce(&mut Self::DecodeMap) -> Result<O, C::Error>,
312    {
313        ensure!(self, hint, ExpectedMap(hint), Value::Map(st) => {
314            f(&mut IterValuePairsDecoder::new(self.cx, st))
315        })
316    }
317
318    #[cfg(feature = "alloc")]
319    #[inline]
320    fn decode_map_hint<F, O>(self, _: &MapHint, f: F) -> Result<O, C::Error>
321    where
322        F: FnOnce(&mut Self::DecodeMapHint) -> Result<O, C::Error>,
323    {
324        ensure!(self, hint, ExpectedMap(hint), Value::Map(map) => {
325            f(&mut IterValuePairsDecoder::new(self.cx, map))
326        })
327    }
328
329    #[cfg(feature = "alloc")]
330    #[inline]
331    fn decode_map_entries(self) -> Result<Self::DecodeMapEntries, C::Error> {
332        ensure!(self, hint, ExpectedMap(hint), Value::Map(map) => {
333            Ok(IterValuePairsDecoder::new(self.cx, map))
334        })
335    }
336
337    #[cfg(feature = "alloc")]
338    #[inline]
339    fn decode_variant<F, O>(self, f: F) -> Result<O, C::Error>
340    where
341        F: FnOnce(&mut Self::DecodeVariant) -> Result<O, C::Error>,
342    {
343        ensure!(self, hint, ExpectedVariant(hint), Value::Variant(st) => {
344            f(&mut IterValueVariantDecoder::new(self.cx, st))
345        })
346    }
347
348    #[inline]
349    fn decode_any<V>(self, visitor: V) -> Result<V::Ok, C::Error>
350    where
351        V: Visitor<'de, Self::Cx>,
352    {
353        match self.value {
354            Value::Unit => visitor.visit_unit(self.cx),
355            Value::Bool(value) => visitor.visit_bool(self.cx, *value),
356            Value::Char(value) => visitor.visit_char(self.cx, *value),
357            Value::Number(number) => match number {
358                Number::U8(value) => visitor.visit_u8(self.cx, *value),
359                Number::U16(value) => visitor.visit_u16(self.cx, *value),
360                Number::U32(value) => visitor.visit_u32(self.cx, *value),
361                Number::U64(value) => visitor.visit_u64(self.cx, *value),
362                Number::U128(value) => visitor.visit_u128(self.cx, *value),
363                Number::I8(value) => visitor.visit_i8(self.cx, *value),
364                Number::I16(value) => visitor.visit_i16(self.cx, *value),
365                Number::I32(value) => visitor.visit_i32(self.cx, *value),
366                Number::I64(value) => visitor.visit_i64(self.cx, *value),
367                Number::I128(value) => visitor.visit_i128(self.cx, *value),
368                Number::Usize(value) => visitor.visit_usize(self.cx, *value),
369                Number::Isize(value) => visitor.visit_isize(self.cx, *value),
370                Number::F32(value) => visitor.visit_f32(self.cx, *value),
371                Number::F64(value) => visitor.visit_f64(self.cx, *value),
372            },
373            #[cfg(feature = "alloc")]
374            Value::Bytes(bytes) => {
375                let visitor = visitor.visit_bytes(self.cx, SizeHint::Exact(bytes.len()))?;
376                visitor.visit_borrowed(self.cx, bytes)
377            }
378            #[cfg(feature = "alloc")]
379            Value::String(string) => {
380                let visitor = visitor.visit_string(self.cx, SizeHint::Exact(string.len()))?;
381                visitor.visit_borrowed(self.cx, string)
382            }
383            #[cfg(feature = "alloc")]
384            Value::Sequence(values) => visitor.visit_sequence(
385                self.cx,
386                &mut IterValueDecoder::<OPT, _>::new(self.cx, values),
387            ),
388            #[cfg(feature = "alloc")]
389            Value::Map(values) => visitor.visit_map(
390                self.cx,
391                &mut IterValuePairsDecoder::<OPT, _>::new(self.cx, values),
392            ),
393            #[cfg(feature = "alloc")]
394            Value::Variant(variant) => visitor.visit_variant(
395                self.cx,
396                &mut IterValueVariantDecoder::<OPT, _>::new(self.cx, variant),
397            ),
398            #[cfg(feature = "alloc")]
399            Value::Option(option) => visitor.visit_option(
400                self.cx,
401                option
402                    .as_ref()
403                    .map(|value| ValueDecoder::<OPT, _>::new(self.cx, value)),
404            ),
405        }
406    }
407}
408
409impl<'a, 'de, C: ?Sized + Context, const OPT: Options> AsDecoder for ValueDecoder<'a, 'de, OPT, C> {
410    type Cx = C;
411    type Decoder<'this> = ValueDecoder<'a, 'this, OPT, C> where Self: 'this;
412
413    #[inline]
414    fn as_decoder(&self) -> Result<Self::Decoder<'_>, C::Error> {
415        Ok(ValueDecoder::new(self.cx, self.value))
416    }
417}
418
419/// A decoder over a simple value iterator.
420
421pub struct IterValueDecoder<'a, 'de, const OPT: Options, C: ?Sized> {
422    cx: &'a C,
423    iter: slice::Iter<'de, Value>,
424}
425
426#[cfg(feature = "alloc")]
427impl<'a, 'de, const OPT: Options, C: ?Sized> IterValueDecoder<'a, 'de, OPT, C> {
428    #[inline]
429    fn new(cx: &'a C, values: &'de [Value]) -> Self {
430        Self {
431            cx,
432            iter: values.iter(),
433        }
434    }
435}
436
437impl<'a, 'de, C: ?Sized + Context, const OPT: Options> SequenceDecoder<'de>
438    for IterValueDecoder<'a, 'de, OPT, C>
439{
440    type Cx = C;
441    type DecodeNext<'this> = ValueDecoder<'a, 'de, OPT, C>
442    where
443        Self: 'this;
444
445    #[inline]
446    fn size_hint(&self) -> SizeHint {
447        SizeHint::from(self.iter.size_hint().1)
448    }
449
450    #[inline]
451    fn try_decode_next(&mut self) -> Result<Option<Self::DecodeNext<'_>>, C::Error> {
452        match self.iter.next() {
453            Some(value) => Ok(Some(ValueDecoder::new(self.cx, value))),
454            None => Ok(None),
455        }
456    }
457
458    #[inline]
459    fn decode_next(&mut self) -> Result<Self::DecodeNext<'_>, C::Error> {
460        match self.iter.next() {
461            Some(value) => Ok(ValueDecoder::new(self.cx, value)),
462            None => Err(self.cx.message(ErrorMessage::ExpectedPackValue)),
463        }
464    }
465}
466
467/// A decoder over a simple value pair iterator.
468pub struct IterValuePairsDecoder<'a, 'de, const OPT: Options, C: ?Sized> {
469    cx: &'a C,
470    iter: slice::Iter<'de, (Value, Value)>,
471}
472
473impl<'a, 'de, const OPT: Options, C: ?Sized> IterValuePairsDecoder<'a, 'de, OPT, C> {
474    #[inline]
475    fn new(cx: &'a C, values: &'de [(Value, Value)]) -> Self {
476        Self {
477            cx,
478            iter: values.iter(),
479        }
480    }
481}
482
483impl<'a, 'de, C: ?Sized + Context, const OPT: Options> MapDecoder<'de>
484    for IterValuePairsDecoder<'a, 'de, OPT, C>
485{
486    type Cx = C;
487    type DecodeEntry<'this> = IterValuePairDecoder<'a, 'de, OPT, C>
488    where
489        Self: 'this;
490    type DecodeRemainingEntries<'this> = IterValuePairsDecoder<'a, 'de, OPT, C> where Self: 'this;
491
492    #[inline]
493    fn size_hint(&self) -> SizeHint {
494        SizeHint::from(self.iter.size_hint().1)
495    }
496
497    #[inline]
498    fn decode_entry(&mut self) -> Result<Option<Self::DecodeEntry<'_>>, C::Error> {
499        let Some(value) = self.iter.next() else {
500            return Ok(None);
501        };
502
503        Ok(Some(IterValuePairDecoder::new(self.cx, value)))
504    }
505
506    #[inline]
507    fn decode_remaining_entries(
508        &mut self,
509    ) -> Result<Self::DecodeRemainingEntries<'_>, <Self::Cx as Context>::Error> {
510        Ok(IterValuePairsDecoder::new(self.cx, self.iter.as_slice()))
511    }
512}
513
514impl<'a, 'de, C: ?Sized + Context, const OPT: Options> EntriesDecoder<'de>
515    for IterValuePairsDecoder<'a, 'de, OPT, C>
516{
517    type Cx = C;
518    type DecodeEntryKey<'this> = ValueDecoder<'a, 'de, OPT, C>
519    where
520        Self: 'this;
521    type DecodeEntryValue<'this> = ValueDecoder<'a, 'de, OPT, C> where Self: 'this;
522
523    #[inline]
524    fn decode_entry_key(&mut self) -> Result<Option<Self::DecodeEntryKey<'_>>, C::Error> {
525        let Some((name, _)) = self.iter.clone().next() else {
526            return Ok(None);
527        };
528
529        Ok(Some(ValueDecoder::with_map_key(self.cx, name)))
530    }
531
532    #[inline]
533    fn decode_entry_value(&mut self) -> Result<Self::DecodeEntryValue<'_>, C::Error> {
534        let Some((_, value)) = self.iter.next() else {
535            return Err(self.cx.message(ErrorMessage::ExpectedMapValue));
536        };
537
538        Ok(ValueDecoder::new(self.cx, value))
539    }
540
541    #[inline]
542    fn end_entries(self) -> Result<(), C::Error> {
543        Ok(())
544    }
545}
546
547impl<'a, 'de, C: ?Sized + Context, const OPT: Options> EntryDecoder<'de>
548    for IterValuePairDecoder<'a, 'de, OPT, C>
549{
550    type Cx = C;
551    type DecodeKey<'this> = ValueDecoder<'a, 'de, OPT, C>
552    where
553        Self: 'this;
554    type DecodeValue = ValueDecoder<'a, 'de, OPT, C>;
555
556    #[inline]
557    fn decode_key(&mut self) -> Result<Self::DecodeKey<'_>, C::Error> {
558        Ok(ValueDecoder::with_map_key(self.cx, &self.pair.0))
559    }
560
561    #[inline]
562    fn decode_value(self) -> Result<Self::DecodeValue, C::Error> {
563        Ok(ValueDecoder::new(self.cx, &self.pair.1))
564    }
565}
566
567/// A decoder over a simple value pair iterator.
568pub struct IterValuePairDecoder<'a, 'de, const OPT: Options, C: ?Sized> {
569    cx: &'a C,
570    pair: &'de (Value, Value),
571}
572
573impl<'a, 'de, const OPT: Options, C: ?Sized> IterValuePairDecoder<'a, 'de, OPT, C> {
574    #[inline]
575    const fn new(cx: &'a C, pair: &'de (Value, Value)) -> Self {
576        Self { cx, pair }
577    }
578}
579
580/// A decoder over a simple value pair as a variant.
581pub struct IterValueVariantDecoder<'a, 'de, const OPT: Options, C: ?Sized> {
582    cx: &'a C,
583    pair: &'de (Value, Value),
584}
585
586#[cfg(feature = "alloc")]
587impl<'a, 'de, const OPT: Options, C: ?Sized> IterValueVariantDecoder<'a, 'de, OPT, C> {
588    #[inline]
589    const fn new(cx: &'a C, pair: &'de (Value, Value)) -> Self {
590        Self { cx, pair }
591    }
592}
593
594impl<'a, 'de, C: ?Sized + Context, const OPT: Options> VariantDecoder<'de>
595    for IterValueVariantDecoder<'a, 'de, OPT, C>
596{
597    type Cx = C;
598    type DecodeTag<'this> = ValueDecoder<'a, 'de, OPT, C>
599    where
600        Self: 'this;
601    type DecodeValue<'this> = ValueDecoder<'a, 'de, OPT, C>
602    where
603        Self: 'this;
604
605    #[inline]
606    fn decode_tag(&mut self) -> Result<Self::DecodeTag<'_>, C::Error> {
607        Ok(ValueDecoder::new(self.cx, &self.pair.0))
608    }
609
610    #[inline]
611    fn decode_value(&mut self) -> Result<Self::DecodeValue<'_>, C::Error> {
612        Ok(ValueDecoder::new(self.cx, &self.pair.1))
613    }
614}
615
616/// Conversion trait for numbers.
617trait FromNumber: Sized {
618    const NUMBER_HINT: NumberHint;
619
620    fn from_number(number: &Number) -> Result<Self, ErrorMessage>;
621
622    fn parse_number(string: &str) -> Option<Self>;
623}
624
625macro_rules! integer_from {
626    ($ty:ty, $variant:ident) => {
627        impl FromNumber for $ty {
628            const NUMBER_HINT: NumberHint = NumberHint::$variant;
629
630            #[inline]
631            fn from_number(number: &Number) -> Result<Self, ErrorMessage> {
632                let out = match number {
633                    Number::U8(n) => Self::try_from(*n).ok(),
634                    Number::U16(n) => Self::try_from(*n).ok(),
635                    Number::U32(n) => Self::try_from(*n).ok(),
636                    Number::U64(n) => Self::try_from(*n).ok(),
637                    Number::U128(n) => Self::try_from(*n).ok(),
638                    Number::I8(n) => Self::try_from(*n).ok(),
639                    Number::I16(n) => Self::try_from(*n).ok(),
640                    Number::I32(n) => Self::try_from(*n).ok(),
641                    Number::I64(n) => Self::try_from(*n).ok(),
642                    Number::I128(n) => Self::try_from(*n).ok(),
643                    Number::Usize(n) => Self::try_from(*n).ok(),
644                    Number::Isize(n) => Self::try_from(*n).ok(),
645                    Number::F32(v) => Some(*v as $ty),
646                    Number::F64(v) => Some(*v as $ty),
647                };
648
649                match out {
650                    Some(out) => Ok(out),
651                    None => Err(ErrorMessage::ExpectedNumber(
652                        Self::NUMBER_HINT,
653                        TypeHint::Number(number.type_hint()),
654                    )),
655                }
656            }
657
658            #[inline]
659            fn parse_number(string: &str) -> Option<Self> {
660                string.parse().ok()
661            }
662        }
663    };
664}
665
666macro_rules! float_from {
667    ($ty:ty, $variant:ident) => {
668        impl FromNumber for $ty {
669            const NUMBER_HINT: NumberHint = NumberHint::$variant;
670
671            #[inline]
672            fn from_number(number: &Number) -> Result<Self, ErrorMessage> {
673                let out = match number {
674                    Number::U8(n) => Some(*n as $ty),
675                    Number::U16(n) => Some(*n as $ty),
676                    Number::U32(n) => Some(*n as $ty),
677                    Number::U64(n) => Some(*n as $ty),
678                    Number::U128(n) => Some(*n as $ty),
679                    Number::I8(n) => Some(*n as $ty),
680                    Number::I16(n) => Some(*n as $ty),
681                    Number::I32(n) => Some(*n as $ty),
682                    Number::I64(n) => Some(*n as $ty),
683                    Number::I128(n) => Some(*n as $ty),
684                    Number::Usize(n) => Some(*n as $ty),
685                    Number::Isize(n) => Some(*n as $ty),
686                    Number::F32(v) => Some(*v as $ty),
687                    Number::F64(v) => Some(*v as $ty),
688                };
689
690                match out {
691                    Some(out) => Ok(out),
692                    None => Err(ErrorMessage::ExpectedNumber(
693                        Self::NUMBER_HINT,
694                        TypeHint::Number(number.type_hint()),
695                    )),
696                }
697            }
698
699            #[inline]
700            fn parse_number(string: &str) -> Option<Self> {
701                string.parse().ok()
702            }
703        }
704    };
705}
706
707integer_from!(u8, U8);
708integer_from!(u16, U16);
709integer_from!(u32, U32);
710integer_from!(u64, U64);
711integer_from!(u128, U128);
712integer_from!(i8, I8);
713integer_from!(i16, I16);
714integer_from!(i32, I32);
715integer_from!(i64, I64);
716integer_from!(i128, I128);
717integer_from!(usize, Usize);
718integer_from!(isize, Isize);
719float_from!(f32, F32);
720float_from!(f64, F64);