1 pub mod exact_size_buf; 2 3 use bytes::{Buf, Bytes, BytesMut}; 4 5 use crate::error::{Error, Result}; 6 7 pub trait MarshalSize { marshal_size(&self) -> usize8 fn marshal_size(&self) -> usize; 9 } 10 11 pub trait Marshal: MarshalSize { marshal_to(&self, buf: &mut [u8]) -> Result<usize>12 fn marshal_to(&self, buf: &mut [u8]) -> Result<usize>; 13 marshal(&self) -> Result<Bytes>14 fn marshal(&self) -> Result<Bytes> { 15 let l = self.marshal_size(); 16 let mut buf = BytesMut::with_capacity(l); 17 buf.resize(l, 0); 18 let n = self.marshal_to(&mut buf)?; 19 if n != l { 20 Err(Error::Other(format!( 21 "marshal_to output size {n}, but expect {l}" 22 ))) 23 } else { 24 Ok(buf.freeze()) 25 } 26 } 27 } 28 29 pub trait Unmarshal: MarshalSize { unmarshal<B>(buf: &mut B) -> Result<Self> where Self: Sized, B: Buf30 fn unmarshal<B>(buf: &mut B) -> Result<Self> 31 where 32 Self: Sized, 33 B: Buf; 34 } 35