musli_core/impls/
range.rs
1use core::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
2
3use crate::en::SequenceEncoder;
4use crate::hint::SequenceHint;
5use crate::{Decode, Decoder, Encode, Encoder};
6
7macro_rules! implement {
8 ($ty:ident $(<$type:ident>)? { $($field:ident),* }, $count:expr) => {
9 impl<M, $($type)*> Encode<M> for $ty $(<$type>)*
10 where
11 $($type: Encode<M>,)*
12 {
13 #[inline]
14 #[allow(unused)]
15 fn encode<E>(&self, _: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
16 where
17 E: Encoder<Mode = M>,
18 {
19 static HINT: SequenceHint = SequenceHint::with_size($count);
20
21 encoder.encode_sequence_fn(&HINT, |tuple| {
22 $(tuple.encode_next()?.encode(&self.$field)?;)*
23 Ok(())
24 })
25 }
26 }
27
28 impl<'de, M, $($type)*> Decode<'de, M> for $ty $(<$type>)*
29 where
30 $($type: Decode<'de, M>,)*
31 {
32 #[inline]
33 fn decode<D>(_: &D::Cx, decoder: D) -> Result<Self, D::Error>
34 where
35 D: Decoder<'de, Mode = M>,
36 {
37 let ($($field,)*) = decoder.decode()?;
38 Ok($ty { $($field,)* })
39 }
40 }
41 }
42}
43
44macro_rules! implement_new {
45 ($ty:ident { $($field:ident),* }, $count:expr) => {
46 impl<M, T> Encode<M> for $ty<T>
47 where
48 T: Encode<M>,
49 {
50 #[inline]
51 fn encode<E>(&self, _: &E::Cx, encoder: E) -> Result<E::Ok, E::Error>
52 where
53 E: Encoder<Mode = M>,
54 {
55 static HINT: SequenceHint = SequenceHint::with_size($count);
56
57 encoder.encode_sequence_fn(&HINT, |tuple| {
58 $(tuple.encode_next()?.encode(self.$field())?;)*
59 Ok(())
60 })
61 }
62 }
63
64 impl<'de, M, T> Decode<'de, M> for $ty<T>
65 where
66 T: Decode<'de, M>,
67 {
68 #[inline]
69 fn decode<D>(cx: &D::Cx, decoder: D) -> Result<Self, D::Error>
70 where
71 D: Decoder<'de, Mode = M>,
72 {
73 let ($($field,)*) = Decode::decode(cx, decoder)?;
74 Ok($ty::new($($field,)*))
75 }
76 }
77 }
78}
79
80implement!(RangeFull {}, 0);
81implement!(Range<T> { start, end }, 2);
82implement!(RangeFrom<T> { start }, 1);
83implement!(RangeTo<T> { end }, 1);
84implement!(RangeToInclusive<T> { end }, 1);
85implement_new!(RangeInclusive { start, end }, 2);