tinycbor/num/
nonzero.rs

1//! `core::num::NonZero*` types.
2use crate::{CborLen, Decode, Decoder, Encode, Encoder};
3
4/// An error that can occur when decoding non-zero numeric types.
5#[derive(#[automatically_derived]
impl<E: ::core::fmt::Debug> ::core::fmt::Debug for Error<E> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Error::Zero => ::core::fmt::Formatter::write_str(f, "Zero"),
            Error::Inner(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Inner",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<E: ::core::clone::Clone> ::core::clone::Clone for Error<E> {
    #[inline]
    fn clone(&self) -> Error<E> {
        match self {
            Error::Zero => Error::Zero,
            Error::Inner(__self_0) =>
                Error::Inner(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<E: ::core::marker::Copy> ::core::marker::Copy for Error<E> { }Copy, #[automatically_derived]
impl<E: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Error<E> {
    #[inline]
    fn eq(&self, other: &Error<E>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Error::Inner(__self_0), Error::Inner(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<E: ::core::cmp::Eq> ::core::cmp::Eq for Error<E> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<E>;
    }
}Eq, #[automatically_derived]
impl<E: ::core::hash::Hash> ::core::hash::Hash for Error<E> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            Error::Inner(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash)]
6pub enum Error<E> {
7    /// Decoded value is zero.
8    Zero,
9    /// An error occurred while decoding the underlying value.
10    Inner(E),
11}
12
13impl<E: core::fmt::Display> core::fmt::Display for Error<E> {
14    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
15        match self {
16            Error::Zero => f.write_fmt(format_args!("decoded value is zero"))write!(f, "decoded value is zero"),
17            Error::Inner(e) => f.write_fmt(format_args!("decoding non-zero value: {0}", e))write!(f, "decoding non-zero value: {}", e),
18        }
19    }
20}
21
22impl<E> From<E> for Error<E> {
23    fn from(e: E) -> Self {
24        Error::Inner(e)
25    }
26}
27
28impl<E: core::error::Error + 'static> core::error::Error for Error<E> {
29    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
30        match self {
31            Error::Zero => None,
32            Error::Inner(e) => Some(e),
33        }
34    }
35}
36
37macro_rules! impl_ {
38    ($($t:ty)*) => {
39        $(
40            impl<'b> Decode<'b> for core::num::NonZero<$t> {
41                type Error = Error<<$t as Decode<'b>>::Error>;
42
43                fn decode(d: &mut Decoder<'b>) -> Result<Self, Self::Error> {
44                    Self::new(Decode::decode(d)?).ok_or_else(|| Error::Zero)
45                }
46            }
47
48            impl Encode for core::num::NonZero<$t> {
49                fn encode<W: embedded_io::Write>(&self, e: &mut Encoder<W>) -> Result<(), W::Error> {
50                    self.get().encode(e)
51                }
52            }
53
54            impl CborLen for core::num::NonZero<$t> {
55                fn cbor_len(&self) -> usize {
56                    self.get().cbor_len()
57                }
58            }
59        )*
60    }
61}
62
63impl<'b> Decode<'b> for core::num::NonZero<isize> {
    type Error = Error<<isize as Decode<'b>>::Error>;
    fn decode(d: &mut Decoder<'b>) -> Result<Self, Self::Error> {
        Self::new(Decode::decode(d)?).ok_or_else(|| Error::Zero)
    }
}
impl Encode for core::num::NonZero<isize> {
    fn encode<W: embedded_io::Write>(&self, e: &mut Encoder<W>)
        -> Result<(), W::Error> {
        self.get().encode(e)
    }
}
impl CborLen for core::num::NonZero<isize> {
    fn cbor_len(&self) -> usize { self.get().cbor_len() }
}impl_! {
64    u16 u32 u64 usize i8 i16 i32 i64 isize
65}
66
67impl<'b> Decode<'b> for core::num::NonZeroU8 {
68    type Error = Error<super::Error>;
69
70    fn decode(d: &mut Decoder<'b>) -> Result<Self, Self::Error> {
71        super::U8::decode(d)?.0.try_into().map_err(|_| Error::Zero)
72    }
73}
74
75impl Encode for core::num::NonZeroU8 {
76    fn encode<W: embedded_io::Write>(&self, e: &mut Encoder<W>) -> Result<(), W::Error> {
77        (self.get() as u64).encode(e)
78    }
79}
80
81impl CborLen for core::num::NonZeroU8 {
82    fn cbor_len(&self) -> usize {
83        (self.get() as u64).cbor_len()
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use crate::{Decode, test};
90    use core::num::*;
91
92    #[test]
93    fn nonzero() {
94        assert!(test(NonZeroU8::new(1).unwrap(), &[0x01]).unwrap());
95        assert!(test(NonZeroU8::new(42).unwrap(), &[0x18, 0x2a]).unwrap());
96        assert!(test(NonZeroU16::new(256).unwrap(), &[0x19, 0x01, 0x00]).unwrap());
97        assert!(
98            test(
99                NonZeroU32::new(65536).unwrap(),
100                &[0x1a, 0x00, 0x01, 0x00, 0x00]
101            )
102            .unwrap()
103        );
104        assert!(test(NonZeroU64::new(1).unwrap(), &[0x01]).unwrap());
105
106        assert!(test(NonZeroI8::new(-1).unwrap(), &[0x20]).unwrap());
107        assert!(test(NonZeroI16::new(-256).unwrap(), &[0x38, 0xff]).unwrap());
108        assert!(test(NonZeroI32::new(100).unwrap(), &[0x18, 0x64]).unwrap());
109        assert!(test(NonZeroI64::new(-1).unwrap(), &[0x20]).unwrap());
110    }
111
112    #[test]
113    fn zero() {
114        use crate::Decoder;
115
116        let cbor = [0x00];
117        let err = NonZeroU8::decode(&mut Decoder(&cbor)).unwrap_err();
118        assert_eq!(err, super::Error::Zero);
119
120        let err = NonZeroU16::decode(&mut Decoder(&cbor)).unwrap_err();
121        assert_eq!(err, super::Error::Zero);
122
123        let err = NonZeroI32::decode(&mut Decoder(&cbor)).unwrap_err();
124        assert_eq!(err, super::Error::Zero);
125    }
126}