Moved from `io::Write` to `bytes::BufMut`, etc. TODO: Move from `io::Read` to `bytes::Buf` (SerializedMessage::<impl MessageValue>::from_buffer(impl Buf)) Fortune for rsh's current commit: Future small blessing − 末小吉message-write-to-buf
parent
6afb148068
commit
52d19c730b
@ -0,0 +1,92 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
Loading…
Reference in new issue