Skip to main content

dilithium_raw/
util.rs

1// Wrapper around a fixed length array of bytes which implements
2// [`serde::Serialize`] and [`serde::Deserialize`] as the *byte array* type in
3// the `serde` data model.
4#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone, Copy)]
5pub struct ByteArray<const N: usize>(pub [u8; N]);
6
7impl<const N: usize> AsRef<[u8; N]> for ByteArray<N> {
8    fn as_ref(&self) -> &[u8; N] {
9        &self.0
10    }
11}
12
13impl<const N: usize> AsMut<[u8; N]> for ByteArray<N> {
14    fn as_mut(&mut self) -> &mut [u8; N] {
15        &mut self.0
16    }
17}
18
19impl<const N: usize> AsRef<[u8]> for ByteArray<N> {
20    fn as_ref(&self) -> &[u8] {
21        &self.0[..]
22    }
23}
24
25impl<const N: usize> AsMut<[u8]> for ByteArray<N> {
26    fn as_mut(&mut self) -> &mut [u8] {
27        &mut self.0[..]
28    }
29}
30
31impl<const N: usize> From<[u8; N]> for ByteArray<N> {
32    fn from(arr: [u8; N]) -> Self {
33        Self(arr)
34    }
35}
36
37impl<const N: usize> ByteArray<N> {
38    pub fn new(arr: [u8; N]) -> Self {
39        Self(arr)
40    }
41}
42
43#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone, Copy)]
44pub struct ByteArrayVec<const N: usize> {
45    pub bytes: [u8; N],
46    pub len: usize,
47}
48
49impl<const N: usize> AsRef<[u8]> for ByteArrayVec<N> {
50    fn as_ref(&self) -> &[u8] {
51        &self.bytes[..self.len]
52    }
53}
54
55impl<const N: usize> AsMut<[u8]> for ByteArrayVec<N> {
56    fn as_mut(&mut self) -> &mut [u8] {
57        &mut self.bytes[..self.len]
58    }
59}
60
61impl<const N: usize> ByteArrayVec<N> {
62    pub fn new(bytes: [u8; N], len: usize) -> Self {
63        Self { bytes, len }
64    }
65}
66
67#[cfg(feature = "serde")]
68pub mod serde {
69    use super::{ByteArray, ByteArrayVec};
70    use core::fmt;
71    use serde::de::{Error, Visitor};
72    use serde::{Deserialize, Deserializer, Serialize, Serializer};
73
74    impl<const N: usize> Serialize for ByteArray<N> {
75        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
76        where
77            S: Serializer,
78        {
79            serializer.serialize_bytes(&self.0[..])
80        }
81    }
82
83    struct ByteArrayVisitor<const N: usize>;
84
85    impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
86        type Value = ByteArray<N>;
87
88        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89            write!(formatter, "a byte array of length {}", N)
90        }
91
92        fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
93            if v.len() == N {
94                let mut bytes = [0; N];
95                bytes[..].copy_from_slice(v);
96                Ok(ByteArray(bytes))
97            } else {
98                Err(E::invalid_length(v.len(), &self))
99            }
100        }
101    }
102
103    impl<'de, const N: usize> Deserialize<'de> for ByteArray<N> {
104        fn deserialize<D>(deserializer: D) -> Result<ByteArray<N>, D::Error>
105        where
106            D: Deserializer<'de>,
107        {
108            deserializer.deserialize_bytes(ByteArrayVisitor)
109        }
110    }
111
112    impl<const N: usize> Serialize for ByteArrayVec<N> {
113        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
114        where
115            S: Serializer,
116        {
117            serializer.serialize_bytes(&self.bytes[..self.len])
118        }
119    }
120
121    struct ByteArrayVecVisitor<const N: usize>;
122
123    impl<'de, const N: usize> Visitor<'de> for ByteArrayVecVisitor<N> {
124        type Value = ByteArrayVec<N>;
125
126        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127            write!(formatter, "a byte array of length at most {}", N)
128        }
129
130        fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
131            let len = v.len();
132            if len <= N {
133                let mut bytes = [0; N];
134                bytes[..len].copy_from_slice(v);
135                Ok(ByteArrayVec { bytes, len })
136            } else {
137                Err(E::invalid_length(len, &self))
138            }
139        }
140    }
141
142    impl<'de, const N: usize> Deserialize<'de> for ByteArrayVec<N> {
143        fn deserialize<D>(deserializer: D) -> Result<ByteArrayVec<N>, D::Error>
144        where
145            D: Deserializer<'de>,
146        {
147            deserializer.deserialize_bytes(ByteArrayVecVisitor)
148        }
149    }
150
151    #[cfg(test)]
152    mod tests {
153        use super::*;
154        use serde_test::{assert_de_tokens_error, assert_tokens, Token};
155
156        #[test]
157        fn test_bytearray_tokens() {
158            let bytes = b"hello";
159            let serde_bytearr = ByteArray(*bytes);
160
161            assert_tokens(&serde_bytearr, &[Token::Bytes(bytes.as_ref())]);
162        }
163
164        #[test]
165        fn test_bytearray_len_error() {
166            let bytes = b"hello";
167
168            assert_de_tokens_error::<ByteArray<4>>(
169                &[Token::Bytes(bytes.as_ref())],
170                "invalid length 5, expected a byte array of length 4",
171            );
172
173            assert_de_tokens_error::<ByteArray<6>>(
174                &[Token::Bytes(bytes.as_ref())],
175                "invalid length 5, expected a byte array of length 6",
176            );
177        }
178
179        #[test]
180        fn test_bytearrayvec_tokens() {
181            let bytes = b"hello\0\0";
182            let serde_bytearrvec = ByteArrayVec {
183                bytes: *bytes,
184                len: 5,
185            };
186
187            assert_tokens(&serde_bytearrvec, &[Token::Bytes(b"hello".as_ref())]);
188        }
189
190        #[test]
191        fn test_bytearrayvec_len_error() {
192            let bytes = b"hello";
193
194            assert_de_tokens_error::<ByteArrayVec<4>>(
195                &[Token::Bytes(bytes.as_ref())],
196                "invalid length 5, expected a byte array of length at most 4",
197            );
198        }
199    }
200}