ecksport-codec 0.3.3

Utils for defining type encodings in the Ecksport RPC library
Documentation
//! Wrapper for Borsh types.

use borsh::{BorshDeserialize, BorshSerialize};

use crate::errors::CodecError;
use crate::traits::RpcCodec;

/// Wrapper type to expose a `borsh`-serializable type in an RPC.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct AsBorsh<T: BorshDeserialize + BorshSerialize>(T);

impl<T: BorshDeserialize + BorshSerialize> AsBorsh<T> {
    pub fn new(v: T) -> Self {
        Self(v)
    }

    pub fn inner(&self) -> &T {
        &self.0
    }

    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.0
    }

    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T: BorshDeserialize + BorshSerialize> From<T> for AsBorsh<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: BorshDeserialize + BorshSerialize> RpcCodec for AsBorsh<T> {
    fn from_slice(buf: &[u8]) -> Result<Self, CodecError> {
        let inst = borsh::from_slice::<T>(buf).map_err(CodecError::Borsh)?;
        Ok(Self(inst))
    }

    fn fill_buf(&self, buf: &mut Vec<u8>) -> Result<(), CodecError> {
        borsh::to_writer(buf, &self.0).map_err(CodecError::Borsh)?;
        Ok(())
    }
}