from_buffer(): Implemented.

Fortune for rsh's current commit: Great blessing − 大吉
message-write-to-buf
Avril 3 years ago
parent 52d19c730b
commit 46cd0e4a9f
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -73,9 +73,75 @@ impl<V: ?Sized + MessageValue> SerializedMessage<V>
/// ///
/// # Panics /// # Panics
/// If `bytes` does not contain enough data to read. /// If `bytes` does not contain enough data to read.
pub fn from_buffer(bytes: impl Buf) -> eyre::Result<Self> pub fn from_buffer(mut bytes: impl Buf) -> eyre::Result<Self>
{ {
todo!() macro_rules! read {
($bref:expr) => {
{
let by: &mut [u8] = ($bref).as_mut();
bytes.copy_to_slice(by);
}
};
(? $odef:expr) => {
{
let by = bytes.get_u8();
match by {
0 => None,
1 => {
let mut def = $odef;
read!(&mut def);
Some(def)
},
x => {
return Err(eyre!("Invalid optional-set bit: {}", x));
}
}
}
};
(: $ser:ty) => {
{
let len = usize::try_from(bytes.get_u64())?;
if len > MAX_ALLOC_SIZE {
return Err(eyre!("Invalid length read: {}", len)
.with_section(|| format!("Max length read: {}", MAX_ALLOC_SIZE)))
}
alloc_local_bytes(len, |de| {
read!(&mut de[..]);
serde_cbor::from_slice::<$ser>(&de[..]).wrap_err(eyre!("Failed to deserialise {} from reader", std::any::type_name::<$ser>()))
})?
}
};
($into:expr, $num:expr) => {
{
let num = $num;
let reader = (&mut bytes).reader();
copy_buffer($into, reader, num).wrap_err(eyre!("Failed to read {} bytes from reader", num))?
}
}
}
let header = read!(: SerHeader);
let data_len = usize::try_from(bytes.get_u64())?;
let mut data = Vec::with_capacity(std::cmp::min(data_len, MAX_ALLOC_SIZE)); //XXX: Redesign so we don't allocate OR try to read massive buffers by accident on corrupted/malformed messages
read!(&mut data, data_len);
if data.len()!=data_len {
return Err(eyre!("Failed to read {} bytes from buffer (got {})", data_len, data.len()));
}
let mut hash = sha256::Sha256Hash::default();
read!(&mut hash);
let enc_key: Option<[u8; RSA_BLOCK_SIZE]> = read!(? [0u8; RSA_BLOCK_SIZE]);
let sig: Option<rsa::Signature> = read!(? rsa::Signature::default());
Ok(Self {
header,
data,
hash,
enc_key,
sig,
_phantom: PhantomData,
})
} }
/// Create from a slice of bytes /// Create from a slice of bytes

Loading…
Cancel
Save