use bornera_core::{RetainedBytes, WriteFrame};
use bytes::Bytes;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OutboundFrame {
bytes: Bytes,
retained: RetainedBytes,
}
impl OutboundFrame {
pub fn new(bytes: Bytes, retained: RetainedBytes) -> Result<Self, OutboundFrameError> {
let visible =
RetainedBytes::try_from(bytes.len()).map_err(|_| OutboundFrameError::LengthOverflow)?;
if retained < visible {
return Err(OutboundFrameError::Underreported { visible, retained });
}
Ok(Self { bytes, retained })
}
pub fn copy_from_slice(bytes: &[u8]) -> Result<Self, OutboundFrameError> {
let retained =
RetainedBytes::try_from(bytes.len()).map_err(|_| OutboundFrameError::LengthOverflow)?;
Ok(Self {
bytes: Bytes::copy_from_slice(bytes),
retained,
})
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Bytes {
self.bytes
}
}
impl WriteFrame for OutboundFrame {
fn bytes(&self) -> &[u8] {
&self.bytes
}
fn retained_bytes(&self) -> RetainedBytes {
self.retained
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OutboundFrameError {
LengthOverflow,
Underreported {
visible: RetainedBytes,
retained: RetainedBytes,
},
}
impl core::fmt::Display for OutboundFrameError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(match self {
Self::LengthOverflow => "frame length exceeds fixed-width retained-byte accounting",
Self::Underreported { .. } => "frame retained bytes are smaller than visible bytes",
})
}
}
impl core::error::Error for OutboundFrameError {}