channels_serdes/
borsh.rs

1//! The [`mod@borsh`] serializer which automatically works with all
2//! types that implement [`borsh::BorshSerialize`] and [`borsh::BorshDeserialize`].
3
4use alloc::vec::Vec;
5
6use borsh::{BorshDeserialize, BorshSerialize};
7
8use crate::{Deserializer, Serializer};
9
10/// The [`mod@borsh`] serializer which automatically works with all
11/// types that implement [`borsh::BorshSerialize`] and [`borsh::BorshDeserialize`].
12#[derive(Debug, Default, Clone)]
13pub struct Borsh {}
14
15impl Borsh {
16	/// Create a new [`Borsh`].
17	#[must_use]
18	pub fn new() -> Self {
19		Self {}
20	}
21}
22
23impl<T> Serializer<T> for Borsh
24where
25	T: BorshSerialize,
26{
27	type Error = borsh::io::Error;
28
29	fn serialize(&mut self, t: &T) -> Result<Vec<u8>, Self::Error> {
30		borsh::to_vec(t)
31	}
32}
33
34impl<T> Deserializer<T> for Borsh
35where
36	T: BorshDeserialize,
37{
38	type Error = borsh::io::Error;
39
40	fn deserialize(
41		&mut self,
42		buf: &mut [u8],
43	) -> Result<T, Self::Error> {
44		borsh::from_slice(buf)
45	}
46}