ecksport_codec/
borsh_wrap.rs

1//! Wrapper for Borsh types.
2
3use borsh::{BorshDeserialize, BorshSerialize};
4
5use crate::errors::CodecError;
6use crate::traits::RpcCodec;
7
8/// Wrapper type to expose a `borsh`-serializable type in an RPC.
9#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
10pub struct AsBorsh<T: BorshDeserialize + BorshSerialize>(T);
11
12impl<T: BorshDeserialize + BorshSerialize> AsBorsh<T> {
13    pub fn new(v: T) -> Self {
14        Self(v)
15    }
16
17    pub fn inner(&self) -> &T {
18        &self.0
19    }
20
21    pub fn inner_mut(&mut self) -> &mut T {
22        &mut self.0
23    }
24
25    pub fn into_inner(self) -> T {
26        self.0
27    }
28}
29
30impl<T: BorshDeserialize + BorshSerialize> From<T> for AsBorsh<T> {
31    fn from(value: T) -> Self {
32        Self::new(value)
33    }
34}
35
36impl<T: BorshDeserialize + BorshSerialize> RpcCodec for AsBorsh<T> {
37    fn from_slice(buf: &[u8]) -> Result<Self, CodecError> {
38        let inst = borsh::from_slice::<T>(buf).map_err(CodecError::Borsh)?;
39        Ok(Self(inst))
40    }
41
42    fn fill_buf(&self, buf: &mut Vec<u8>) -> Result<(), CodecError> {
43        borsh::to_writer(buf, &self.0).map_err(CodecError::Borsh)?;
44        Ok(())
45    }
46}