serde_jam/with/
bytes.rs

1//! Serialize and deserialize fixed byte array that larger than 32 bytes.
2
3use crate::{Vec, visitor::FixedBytesVisitor};
4use serde::{de, de::Error, ser, ser::SerializeSeq};
5
6/// Serialize fixed byte array that larger than 32 bytes.
7pub fn serialize<S: serde::ser::Serializer, T: AsRef<[u8]>>(
8    value: &T,
9    serializer: S,
10) -> core::result::Result<S::Ok, S::Error> {
11    serializer.serialize_bytes(value.as_ref())
12}
13
14/// Deserialize fixed byte array that larger than 32 bytes.
15pub fn deserialize<'de, D: serde::de::Deserializer<'de>, T: TryFrom<Vec<u8>>>(
16    deserializer: D,
17) -> core::result::Result<T, D::Error> {
18    deserializer.deserialize_tuple(core::mem::size_of::<T>(), FixedBytesVisitor::<T>::new())
19}
20
21/// Serialize and deserialize fixed byte array that larger than 32 bytes.
22pub mod array {
23    use super::*;
24    use core::fmt;
25
26    /// Serialize array of fixed byte arrays
27    pub fn serialize<S: ser::Serializer, T: AsRef<[u8]>>(
28        value: &[T],
29        serializer: S,
30    ) -> core::result::Result<S::Ok, S::Error> {
31        let mut seq = serializer.serialize_seq(Some(value.len()))?;
32        for item in value {
33            seq.serialize_element(item.as_ref())?;
34        }
35        seq.end()
36    }
37
38    /// Deserialize array of fixed byte arrays
39    pub fn deserialize<'de, D: de::Deserializer<'de>, T: TryFrom<Vec<u8>>>(
40        deserializer: D,
41    ) -> core::result::Result<Vec<T>, D::Error> {
42        deserializer.deserialize_seq(FixedArrayVisitor::<T>::new())
43    }
44
45    /// Visitor for arrays of fixed-size byte arrays
46    #[derive(Default)]
47    struct FixedArrayVisitor<T: TryFrom<Vec<u8>>> {
48        _marker: core::marker::PhantomData<T>,
49    }
50
51    impl<T: TryFrom<Vec<u8>>> FixedArrayVisitor<T> {
52        fn new() -> Self {
53            Self {
54                _marker: core::marker::PhantomData,
55            }
56        }
57    }
58
59    impl<'de, T: TryFrom<Vec<u8>>> de::Visitor<'de> for FixedArrayVisitor<T> {
60        type Value = Vec<T>;
61
62        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
63            formatter.write_str("a sequence of fixed-size byte arrays")
64        }
65
66        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
67        where
68            A: de::SeqAccess<'de>,
69        {
70            let mut result = Vec::new();
71            while let Some(bytes) = seq.next_element::<Vec<u8>>()? {
72                let item = T::try_from(bytes)
73                    .map_err(|_| A::Error::custom("failed to convert bytes to fixed array"))?;
74                result.push(item);
75            }
76            Ok(result)
77        }
78    }
79}