//! Creating binary from messages //! //! `SerializedMessage` to `Bytes`. use super::*; use bytes::{ Bytes, BytesMut, BufMut, Buf, }; impl SerializedMessage { /// Write this message to a buffer /// /// # Panics /// If `buffer` cannot hold enough bytes. pub fn into_buffer(self, mut buffer: impl BufMut) -> eyre::Result { let mut w=0; macro_rules! write { ($bytes:expr) => { { let slice: &[u8] = ($bytes).as_ref(); buffer.put_slice(slice); w+=slice.len(); } }; (? $o:expr) => { { match $o { Some(opt) => { buffer.put_u8(1); write!(opt); }, None => {buffer.put_u8(0);}, } w+=1; } }; (: $ser:expr) => { { let mut v = StackVec::new(); serde_cbor::to_writer(&mut v, $ser)?; buffer.put_u64(v.len().try_into()?); write!(&v[..]); } }; } write!(: &self.header); buffer.put_u64(self.data.len().try_into()?); write!(self.data); write!(self.hash); write!(? self.enc_key); write!(? self.sig); Ok(w) } /// Write this message to a new `Bytes`. pub fn into_bytes(self) -> eyre::Result { let mut output = BytesMut::with_capacity(4096); //TODO: Find a better default capacity for this. self.into_buffer(&mut output)?; Ok(output.freeze()) } } impl SerializedMessage { /// Create from a buffer of bytes. /// /// # Panics /// If `bytes` does not contain enough data to read. pub fn from_buffer(bytes: impl Buf) -> eyre::Result { todo!() } /// Create from a slice of bytes #[inline] pub fn from_slice(bytes: impl AsRef<[u8]>) -> eyre::Result { Self::from_buffer(bytes.as_ref()) } /// Create from a `Bytes` instance #[inline(always)] pub fn from_bytes(bytes: Bytes) -> eyre::Result { Self::from_buffer(bytes) } }