alloy_primitives/signed/
serde.rs

1use super::Signed;
2use alloc::string::String;
3use core::{fmt, str};
4use ruint::Uint;
5use serde::{
6    Deserialize, Deserializer, Serialize, Serializer,
7    de::{self, Visitor},
8};
9
10impl<const BITS: usize, const LIMBS: usize> Serialize for Signed<BITS, LIMBS> {
11    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
12        if serializer.is_human_readable() {
13            serializer.collect_str(self)
14        } else {
15            self.into_raw().serialize(serializer)
16        }
17    }
18}
19
20impl<'de, const BITS: usize, const LIMBS: usize> Deserialize<'de> for Signed<BITS, LIMBS> {
21    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
22        deserialize(deserializer)
23    }
24}
25
26fn deserialize<'de, const BITS: usize, const LIMBS: usize, D: Deserializer<'de>>(
27    deserializer: D,
28) -> Result<Signed<BITS, LIMBS>, D::Error> {
29    struct SignedVisitor<const BITS: usize, const LIMBS: usize>;
30
31    impl<const BITS: usize, const LIMBS: usize> Visitor<'_> for SignedVisitor<BITS, LIMBS> {
32        type Value = Signed<BITS, LIMBS>;
33
34        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35            write!(f, "a {BITS} bit signed integer")
36        }
37
38        fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
39            Signed::try_from(v).map_err(de::Error::custom)
40        }
41
42        fn visit_u128<E: de::Error>(self, v: u128) -> Result<Self::Value, E> {
43            Signed::try_from(v).map_err(de::Error::custom)
44        }
45
46        fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
47            Signed::try_from(v).map_err(de::Error::custom)
48        }
49
50        fn visit_i128<E: de::Error>(self, v: i128) -> Result<Self::Value, E> {
51            Signed::try_from(v).map_err(de::Error::custom)
52        }
53
54        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
55            v.parse().map_err(serde::de::Error::custom)
56        }
57
58        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
59            self.visit_str(&v)
60        }
61    }
62
63    if deserializer.is_human_readable() {
64        deserializer.deserialize_any(SignedVisitor)
65    } else {
66        Uint::<BITS, LIMBS>::deserialize(deserializer).map(Signed::from_raw)
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use crate::I256;
73    use core::str::FromStr;
74
75    const TEST_VALS: [&str; 5] = [
76        "12345681238128738123",
77        "-1239373781294184527124318238",
78        "99999999999999999999999999999999999999999999999999999999999",
79        "57896044618658097711785492504343953926634992332820282019728792003956564819967",
80        "-57896044618658097711785492504343953926634992332820282019728792003956564819968",
81    ];
82
83    #[test]
84    fn serde_json_roundtrip() {
85        for val in TEST_VALS {
86            let signed = I256::from_str(val).unwrap();
87            let ser = serde_json::to_string(&signed).unwrap();
88            assert_eq!(serde_json::from_str::<I256>(&ser).unwrap(), signed);
89            assert_eq!(serde_json::from_str::<I256>(&format!("\"{val}\"")).unwrap(), signed);
90        }
91    }
92
93    #[test]
94    fn serde_bincode_roundtrip() {
95        for val in TEST_VALS {
96            let signed = I256::from_str(val).unwrap();
97            let ser = bincode::serialize(&signed).unwrap();
98            assert!(ser.len() <= 64);
99            assert_eq!(bincode::deserialize::<I256>(&ser).unwrap(), signed);
100        }
101    }
102}