junobuild_utils/serializers/
bigint.rs

1use crate::serializers::types::DocDataBigInt;
2use serde::de::{self, MapAccess, Visitor};
3use serde::ser::SerializeStruct;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6
7impl fmt::Display for DocDataBigInt {
8    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9        write!(f, "{}", self.value)
10    }
11}
12
13impl Serialize for DocDataBigInt {
14    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
15    where
16        S: Serializer,
17    {
18        let mut state = serializer.serialize_struct("DocDataBigInt", 1)?;
19        state.serialize_field("__bigint__", &self.value.to_string())?;
20        state.end()
21    }
22}
23
24impl<'de> Deserialize<'de> for DocDataBigInt {
25    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
26    where
27        D: Deserializer<'de>,
28    {
29        deserializer.deserialize_struct("DocDataBigInt", &["__bigint__"], DocDataBigIntVisitor)
30    }
31}
32
33struct DocDataBigIntVisitor;
34
35impl<'de> Visitor<'de> for DocDataBigIntVisitor {
36    type Value = DocDataBigInt;
37
38    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
39        formatter.write_str("an object with a key __bigint__")
40    }
41
42    fn visit_map<V>(self, mut map: V) -> Result<DocDataBigInt, V::Error>
43    where
44        V: MapAccess<'de>,
45    {
46        let mut value = None;
47        while let Some(key) = map.next_key::<String>()? {
48            if key == "__bigint__" {
49                if value.is_some() {
50                    return Err(de::Error::duplicate_field("__bigint__"));
51                }
52                value = Some(map.next_value::<String>()?);
53            }
54        }
55        let value_str = value.ok_or_else(|| de::Error::missing_field("__bigint__"))?;
56        let bigint_value = value_str
57            .parse::<u64>()
58            .map_err(|_| de::Error::custom("Invalid format for __bigint__"))?;
59        Ok(DocDataBigInt {
60            value: bigint_value,
61        })
62    }
63}