You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
1.9 KiB
93 lines
1.9 KiB
//! Creating binary from messages
|
|
//!
|
|
//! `SerializedMessage` to `Bytes`.
|
|
use super::*;
|
|
use bytes::{
|
|
Bytes,
|
|
BytesMut,
|
|
BufMut,
|
|
Buf,
|
|
};
|
|
|
|
impl<V: ?Sized> SerializedMessage<V>
|
|
{
|
|
/// Write this message to a buffer
|
|
///
|
|
/// # Panics
|
|
/// If `buffer` cannot hold enough bytes.
|
|
pub fn into_buffer(self, mut buffer: impl BufMut) -> eyre::Result<usize>
|
|
{
|
|
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<Bytes>
|
|
{
|
|
let mut output = BytesMut::with_capacity(4096); //TODO: Find a better default capacity for this.
|
|
self.into_buffer(&mut output)?;
|
|
Ok(output.freeze())
|
|
}
|
|
}
|
|
|
|
impl<V: ?Sized + MessageValue> SerializedMessage<V>
|
|
{
|
|
/// 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<Self>
|
|
{
|
|
todo!()
|
|
}
|
|
|
|
/// Create from a slice of bytes
|
|
#[inline] pub fn from_slice(bytes: impl AsRef<[u8]>) -> eyre::Result<Self>
|
|
{
|
|
Self::from_buffer(bytes.as_ref())
|
|
}
|
|
|
|
/// Create from a `Bytes` instance
|
|
#[inline(always)] pub fn from_bytes(bytes: Bytes) -> eyre::Result<Self>
|
|
{
|
|
Self::from_buffer(bytes)
|
|
}
|
|
}
|