binius_utils/
serialization.rs

1// Copyright 2024-2025 Irreducible Inc.
2
3use bytes::{Buf, BufMut};
4use generic_array::{ArrayLength, GenericArray};
5use thiserror::Error;
6
7/// Serialize data according to Mode param
8pub trait SerializeBytes {
9	fn serialize(&self, write_buf: impl BufMut) -> Result<(), SerializationError>;
10}
11
12/// Deserialize data according to Mode param
13pub trait DeserializeBytes {
14	fn deserialize(read_buf: impl Buf) -> Result<Self, SerializationError>
15	where
16		Self: Sized;
17}
18
19#[derive(Error, Debug, Clone)]
20pub enum SerializationError {
21	#[error("Write buffer is full")]
22	WriteBufferFull,
23	#[error("Not enough data in read buffer to deserialize")]
24	NotEnoughBytes,
25	#[error("Unknown enum variant index {name}::{index}")]
26	UnknownEnumVariant { name: &'static str, index: u8 },
27	#[error("Serialization has not been implemented")]
28	SerializationNotImplemented,
29	#[error("Deserializer has not been implemented")]
30	DeserializerNotImplemented,
31	#[error("Multiple deserializers with the same name {name} has been registered")]
32	DeserializerNameConflict { name: String },
33	#[error("FromUtf8Error: {0}")]
34	FromUtf8Error(#[from] std::string::FromUtf8Error),
35	#[error("Invalid construction of {name}")]
36	InvalidConstruction { name: &'static str },
37	#[error("usize {size} is too large to serialize (max is {max})", max = u32::MAX)]
38	UsizeTooLarge { size: usize },
39}
40
41impl<T: SerializeBytes + ?Sized> SerializeBytes for &T {
42	fn serialize(&self, write_buf: impl BufMut) -> Result<(), SerializationError> {
43		(**self).serialize(write_buf)
44	}
45}
46
47impl SerializeBytes for usize {
48	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
49		let value: u32 = (*self)
50			.try_into()
51			.map_err(|_| SerializationError::UsizeTooLarge { size: *self })?;
52		SerializeBytes::serialize(&value, &mut write_buf)
53	}
54}
55
56impl DeserializeBytes for usize {
57	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
58	where
59		Self: Sized,
60	{
61		let value: u32 = DeserializeBytes::deserialize(&mut read_buf)?;
62		Ok(value as Self)
63	}
64}
65
66impl SerializeBytes for u128 {
67	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
68		assert_enough_space_for(&write_buf, std::mem::size_of::<Self>())?;
69		write_buf.put_u128_le(*self);
70		Ok(())
71	}
72}
73
74impl DeserializeBytes for u128 {
75	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
76	where
77		Self: Sized,
78	{
79		assert_enough_data_for(&read_buf, std::mem::size_of::<Self>())?;
80		Ok(read_buf.get_u128_le())
81	}
82}
83
84impl SerializeBytes for u64 {
85	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
86		assert_enough_space_for(&write_buf, std::mem::size_of::<Self>())?;
87		write_buf.put_u64_le(*self);
88		Ok(())
89	}
90}
91
92impl DeserializeBytes for u64 {
93	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
94	where
95		Self: Sized,
96	{
97		assert_enough_data_for(&read_buf, std::mem::size_of::<Self>())?;
98		Ok(read_buf.get_u64_le())
99	}
100}
101
102impl SerializeBytes for u32 {
103	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
104		assert_enough_space_for(&write_buf, std::mem::size_of::<Self>())?;
105		write_buf.put_u32_le(*self);
106		Ok(())
107	}
108}
109
110impl DeserializeBytes for u32 {
111	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
112	where
113		Self: Sized,
114	{
115		assert_enough_data_for(&read_buf, std::mem::size_of::<Self>())?;
116		Ok(read_buf.get_u32_le())
117	}
118}
119
120impl SerializeBytes for u16 {
121	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
122		assert_enough_space_for(&write_buf, std::mem::size_of::<Self>())?;
123		write_buf.put_u16_le(*self);
124		Ok(())
125	}
126}
127
128impl DeserializeBytes for u16 {
129	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
130	where
131		Self: Sized,
132	{
133		assert_enough_data_for(&read_buf, std::mem::size_of::<Self>())?;
134		Ok(read_buf.get_u16_le())
135	}
136}
137
138impl SerializeBytes for u8 {
139	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
140		assert_enough_space_for(&write_buf, std::mem::size_of::<Self>())?;
141		write_buf.put_u8(*self);
142		Ok(())
143	}
144}
145
146impl DeserializeBytes for u8 {
147	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
148	where
149		Self: Sized,
150	{
151		assert_enough_data_for(&read_buf, std::mem::size_of::<Self>())?;
152		Ok(read_buf.get_u8())
153	}
154}
155
156impl SerializeBytes for bool {
157	fn serialize(&self, write_buf: impl BufMut) -> Result<(), SerializationError> {
158		u8::serialize(&(*self as u8), write_buf)
159	}
160}
161
162impl DeserializeBytes for bool {
163	fn deserialize(read_buf: impl Buf) -> Result<Self, SerializationError>
164	where
165		Self: Sized,
166	{
167		Ok(u8::deserialize(read_buf)? != 0)
168	}
169}
170
171impl<T> SerializeBytes for std::marker::PhantomData<T> {
172	fn serialize(&self, _write_buf: impl BufMut) -> Result<(), SerializationError> {
173		Ok(())
174	}
175}
176
177impl<T> DeserializeBytes for std::marker::PhantomData<T> {
178	fn deserialize(_read_buf: impl Buf) -> Result<Self, SerializationError>
179	where
180		Self: Sized,
181	{
182		Ok(Self)
183	}
184}
185
186impl SerializeBytes for &str {
187	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
188		let bytes = self.as_bytes();
189		SerializeBytes::serialize(&bytes.len(), &mut write_buf)?;
190		assert_enough_space_for(&write_buf, bytes.len())?;
191		write_buf.put_slice(bytes);
192		Ok(())
193	}
194}
195
196impl SerializeBytes for String {
197	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
198		SerializeBytes::serialize(&self.as_str(), &mut write_buf)
199	}
200}
201
202impl DeserializeBytes for String {
203	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
204	where
205		Self: Sized,
206	{
207		let len = DeserializeBytes::deserialize(&mut read_buf)?;
208		assert_enough_data_for(&read_buf, len)?;
209		Ok(Self::from_utf8(read_buf.copy_to_bytes(len).to_vec())?)
210	}
211}
212
213impl<T: SerializeBytes> SerializeBytes for [T] {
214	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
215		SerializeBytes::serialize(&self.len(), &mut write_buf)?;
216		self.iter()
217			.try_for_each(|item| SerializeBytes::serialize(item, &mut write_buf))
218	}
219}
220
221impl<T: SerializeBytes> SerializeBytes for Vec<T> {
222	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
223		SerializeBytes::serialize(self.as_slice(), &mut write_buf)
224	}
225}
226
227impl<T: DeserializeBytes> DeserializeBytes for Vec<T> {
228	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
229	where
230		Self: Sized,
231	{
232		let len: usize = DeserializeBytes::deserialize(&mut read_buf)?;
233		(0..len)
234			.map(|_| DeserializeBytes::deserialize(&mut read_buf))
235			.collect()
236	}
237}
238
239impl<T: SerializeBytes> SerializeBytes for Option<T> {
240	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
241		match self {
242			Some(value) => {
243				SerializeBytes::serialize(&true, &mut write_buf)?;
244				SerializeBytes::serialize(value, &mut write_buf)?;
245			}
246			None => {
247				SerializeBytes::serialize(&false, write_buf)?;
248			}
249		}
250		Ok(())
251	}
252}
253
254impl<T: DeserializeBytes> DeserializeBytes for Option<T> {
255	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
256	where
257		Self: Sized,
258	{
259		Ok(match bool::deserialize(&mut read_buf)? {
260			true => Some(T::deserialize(&mut read_buf)?),
261			false => None,
262		})
263	}
264}
265
266impl<U: SerializeBytes, V: SerializeBytes> SerializeBytes for (U, V) {
267	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
268		U::serialize(&self.0, &mut write_buf)?;
269		V::serialize(&self.1, write_buf)
270	}
271}
272
273impl<U: DeserializeBytes, V: DeserializeBytes> DeserializeBytes for (U, V) {
274	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
275	where
276		Self: Sized,
277	{
278		Ok((U::deserialize(&mut read_buf)?, V::deserialize(read_buf)?))
279	}
280}
281
282impl<N: ArrayLength<u8>> SerializeBytes for GenericArray<u8, N> {
283	fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
284		assert_enough_space_for(&write_buf, N::USIZE)?;
285		write_buf.put_slice(self);
286		Ok(())
287	}
288}
289
290impl<N: ArrayLength<u8>> DeserializeBytes for GenericArray<u8, N> {
291	fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError> {
292		assert_enough_data_for(&read_buf, N::USIZE)?;
293		let mut ret = Self::default();
294		read_buf.copy_to_slice(&mut ret);
295		Ok(ret)
296	}
297}
298
299#[inline]
300pub fn assert_enough_space_for(
301	write_buf: &impl BufMut,
302	size: usize,
303) -> Result<(), SerializationError> {
304	if write_buf.remaining_mut() < size {
305		return Err(SerializationError::WriteBufferFull);
306	}
307	Ok(())
308}
309
310#[inline]
311pub fn assert_enough_data_for(read_buf: &impl Buf, size: usize) -> Result<(), SerializationError> {
312	if read_buf.remaining() < size {
313		return Err(SerializationError::NotEnoughBytes);
314	}
315	Ok(())
316}
317
318#[cfg(test)]
319mod tests {
320	use generic_array::typenum::U32;
321	use rand::{RngCore, SeedableRng, rngs::StdRng};
322
323	use super::*;
324
325	#[test]
326	fn test_generic_array_serialize_deserialize() {
327		let mut rng = StdRng::seed_from_u64(0);
328
329		let mut data = GenericArray::<u8, U32>::default();
330		rng.fill_bytes(&mut data);
331
332		let mut buf = Vec::new();
333		data.serialize(&mut buf).unwrap();
334
335		let data_deserialized = GenericArray::<u8, U32>::deserialize(&mut buf.as_slice()).unwrap();
336		assert_eq!(data_deserialized, data);
337	}
338}