Skip to main content

byte_unit/bit/
serde_traits.rs

1use alloc::format;
2use core::{
3    fmt::{self, Formatter},
4    str::FromStr,
5};
6
7use serde::{
8    self,
9    de::{Error as DeError, Unexpected, Visitor},
10    Deserialize, Deserializer, Serialize, Serializer,
11};
12
13use super::Bit;
14#[cfg(feature = "u128")]
15use super::RONNABIT;
16
17impl Serialize for Bit {
18    #[inline]
19    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
20    where
21        S: Serializer, {
22        if serializer.is_human_readable() {
23            serializer.serialize_str(format!("{self:#}").as_str())
24        } else {
25            serializer.serialize_u128(self.as_u128())
26        }
27    }
28}
29
30impl<'de> Deserialize<'de> for Bit {
31    #[inline]
32    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
33    where
34        D: Deserializer<'de>, {
35        struct MyVisitor;
36
37        impl<'de> Visitor<'de> for MyVisitor {
38            type Value = Bit;
39
40            #[inline]
41            fn expecting(&self, f: &mut Formatter<'_>) -> fmt::Result {
42                f.write_str("a string such as \"123\", \"123Kib\", \"50.84 Mb\", or ")?;
43
44                #[cfg(feature = "u128")]
45                {
46                    f.write_fmt(format_args!("a positive integer smaller than {RONNABIT}"))
47                }
48
49                #[cfg(not(feature = "u128"))]
50                {
51                    f.write_fmt(format_args!(
52                        "a positive integer smaller than {}",
53                        u64::MAX as u128 + 1
54                    ))
55                }
56            }
57
58            #[inline]
59            fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
60            where
61                E: DeError, {
62                Bit::from_u128(v).ok_or_else(|| {
63                    DeError::invalid_value(Unexpected::Other(format!("{v}").as_str()), &self)
64                })
65            }
66
67            #[inline]
68            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
69            where
70                E: DeError, {
71                Bit::from_str(v).map_err(DeError::custom)
72            }
73        }
74
75        if deserializer.is_human_readable() {
76            deserializer.deserialize_str(MyVisitor)
77        } else {
78            deserializer.deserialize_u128(MyVisitor)
79        }
80    }
81}