use alloc::vec::Vec;
use bytes::Bytes;
use crate::view::{ViewLifetimeParametric, ViewReborrow};
use crate::{DecodeError, DecodeOptions, EncodeSink, Message, MessageView, OwnedView};
use super::{ZeroizeOnDrop, Zeroizing};
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum GuardedViewError {
#[error("guarded view size limit exceeded")]
SizeLimit,
#[error("could not reserve guarded view storage")]
Allocation,
#[error("guarded view encoding length mismatch")]
EncodingLength,
#[error("guarded view decode failed: {0}")]
Decode(#[from] DecodeError),
}
pub struct GuardedOwnedView<V> {
inner: OwnedView<V>,
}
struct WireOwner(Zeroizing<Vec<u8>>);
impl AsRef<[u8]> for WireOwner {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
struct WireSink {
bytes: Zeroizing<Vec<u8>>,
expected_len: usize,
overrun: bool,
}
impl WireSink {
fn new(expected_len: usize) -> Result<Self, GuardedViewError> {
let mut bytes = Zeroizing::new(Vec::new());
bytes
.try_reserve_exact(expected_len)
.map_err(|_| GuardedViewError::Allocation)?;
Ok(Self {
bytes,
expected_len,
overrun: false,
})
}
fn finish(self) -> Result<WireOwner, GuardedViewError> {
if self.overrun || self.bytes.len() != self.expected_len {
return Err(GuardedViewError::EncodingLength);
}
Ok(WireOwner(self.bytes))
}
}
impl EncodeSink for WireSink {
fn put_u8(&mut self, byte: u8) {
self.put_slice(core::slice::from_ref(&byte));
}
fn put_slice(&mut self, source: &[u8]) {
if self.overrun {
return;
}
if self
.bytes
.len()
.checked_add(source.len())
.is_some_and(|len| len <= self.expected_len)
{
self.bytes.extend_from_slice(source);
} else {
self.overrun = true;
}
}
fn put_u32_le(&mut self, value: u32) {
self.put_slice(&value.to_le_bytes());
}
fn put_u64_le(&mut self, value: u64) {
self.put_slice(&value.to_le_bytes());
}
}
impl<V: ViewLifetimeParametric> GuardedOwnedView<V> {
pub fn decode(source: &[u8], options: &DecodeOptions) -> Result<Self, GuardedViewError> {
Self::check_size(source.len(), options)?;
let mut sink = WireSink::new(source.len())?;
sink.put_slice(source);
Self::admit(sink.finish()?, options)
}
pub fn from_owned(
message: &V::Owned,
options: &DecodeOptions,
) -> Result<Self, GuardedViewError> {
let mut cache = crate::SizeCache::new();
let size = usize::try_from(message.compute_size(&mut cache))
.map_err(|_| GuardedViewError::SizeLimit)?;
Self::check_size(size, options)?;
let mut sink = WireSink::new(size)?;
message.write_to(&mut cache, &mut sink);
Self::admit(sink.finish()?, options)
}
fn check_size(size: usize, options: &DecodeOptions) -> Result<(), GuardedViewError> {
if size > options.max_message_size() {
Err(GuardedViewError::SizeLimit)
} else {
Ok(())
}
}
fn admit(owner: WireOwner, options: &DecodeOptions) -> Result<Self, GuardedViewError> {
let inner = OwnedView::decode_with_options(Bytes::from_owner(owner), options)?;
Ok(Self { inner })
}
}
impl<V: ViewReborrow> GuardedOwnedView<V> {
#[must_use]
pub fn view(&self) -> &V::Reborrowed<'_> {
self.inner.reborrow()
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
self.inner.bytes()
}
pub fn to_owned_message(&self) -> Result<V::Owned, DecodeError> {
self.view().to_owned_message()
}
}
impl<V> core::fmt::Debug for GuardedOwnedView<V> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("GuardedOwnedView([REDACTED])")
}
}
impl<V: ZeroizeOnDrop> ZeroizeOnDrop for GuardedOwnedView<V> {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounded_sink_rejects_length_mismatches() {
let mut overrun = WireSink::new(2).unwrap();
overrun.put_u8(1);
overrun.put_slice(&[2, 3]);
overrun.put_u8(4);
assert_eq!(overrun.bytes.as_slice(), [1]);
assert!(matches!(
overrun.finish(),
Err(GuardedViewError::EncodingLength)
));
let mut underrun = WireSink::new(2).unwrap();
underrun.put_u8(1);
assert!(matches!(
underrun.finish(),
Err(GuardedViewError::EncodingLength)
));
}
}