pub trait Packet: Clone + Sized + Send + 'static {
fn parse(buf: &mut Vec<u8>) -> Option<Self>;
fn to_bytes(&self) -> Vec<u8>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Bytes(pub Vec<u8>);
impl Packet for Bytes {
fn parse(buf: &mut Vec<u8>) -> Option<Self> {
if buf.is_empty() {
None
} else {
Some(Bytes(std::mem::take(buf)))
}
}
fn to_bytes(&self) -> Vec<u8> {
self.0.clone()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Line(pub String);
impl Packet for Line {
fn parse(buf: &mut Vec<u8>) -> Option<Self> {
let end = buf.iter().position(|&b| b == b'\n')?;
let line: Vec<u8> = buf.drain(..=end).collect();
Some(Line(
String::from_utf8_lossy(&line[..line.len() - 1]).into_owned(),
))
}
fn to_bytes(&self) -> Vec<u8> {
let mut bytes = self.0.clone().into_bytes();
bytes.push(b'\n');
bytes
}
}
pub trait Delimiter: Send + 'static {
const DELIMITER: &'static [u8];
}
#[derive(Debug)]
pub struct Lf;
impl Delimiter for Lf {
const DELIMITER: &'static [u8] = b"\n";
}
#[derive(Debug)]
pub struct Cr;
impl Delimiter for Cr {
const DELIMITER: &'static [u8] = b"\r";
}
#[derive(Debug)]
pub struct CrLf;
impl Delimiter for CrLf {
const DELIMITER: &'static [u8] = b"\r\n";
}
pub struct Delimited<D: Delimiter = Lf> {
frame: Vec<u8>,
delimiter: std::marker::PhantomData<fn() -> D>,
}
impl<D: Delimiter> Delimited<D> {
pub fn new(body: impl Into<Vec<u8>>) -> Self {
let mut frame = body.into();
frame.extend_from_slice(D::DELIMITER);
Self::from_frame(frame)
}
pub fn from_frame(frame: impl Into<Vec<u8>>) -> Self {
Delimited {
frame: frame.into(),
delimiter: std::marker::PhantomData,
}
}
pub fn frame(&self) -> &[u8] {
&self.frame
}
pub fn body(&self) -> &[u8] {
self.frame.strip_suffix(D::DELIMITER).unwrap_or(&self.frame)
}
pub fn text(&self) -> std::borrow::Cow<'_, str> {
String::from_utf8_lossy(self.body())
}
pub fn into_frame(self) -> Vec<u8> {
self.frame
}
}
impl<D: Delimiter> Clone for Delimited<D> {
fn clone(&self) -> Self {
Self::from_frame(self.frame.clone())
}
}
impl<D: Delimiter> PartialEq for Delimited<D> {
fn eq(&self, other: &Self) -> bool {
self.frame == other.frame
}
}
impl<D: Delimiter> Eq for Delimited<D> {}
impl<D: Delimiter> std::fmt::Debug for Delimited<D> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Delimited")
.field(&self.frame.escape_ascii().to_string())
.finish()
}
}
impl<D: Delimiter> Packet for Delimited<D> {
fn parse(buf: &mut Vec<u8>) -> Option<Self> {
let delimiter = D::DELIMITER;
assert!(!delimiter.is_empty(), "a Delimiter must not be empty");
let start = buf.windows(delimiter.len()).position(|w| w == delimiter)?;
Some(Self::from_frame(
buf.drain(..start + delimiter.len()).collect::<Vec<u8>>(),
))
}
fn to_bytes(&self) -> Vec<u8> {
self.frame.clone()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Endian {
Big,
Little,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LengthField {
pub offset: usize,
pub width: usize,
pub endian: Endian,
pub adjust: i64,
}
impl LengthField {
pub fn frame_len(&self, buf: &[u8]) -> Option<usize> {
assert!(
matches!(self.width, 1 | 2 | 4 | 8),
"LengthField width must be 1, 2, 4 or 8 bytes, not {}",
self.width
);
let end = self.offset + self.width;
let field = buf.get(self.offset..end)?;
let mut bytes = [0u8; 8];
let value = match self.endian {
Endian::Big => {
bytes[8 - self.width..].copy_from_slice(field);
u64::from_be_bytes(bytes)
}
Endian::Little => {
bytes[..self.width].copy_from_slice(field);
u64::from_le_bytes(bytes)
}
};
let total = i128::from(value) + i128::from(self.adjust);
assert!(
total >= end as i128,
"length field {value} at offset {} gives a {total}-byte frame, shorter than the \
{end} bytes up to the end of the field",
self.offset
);
Some(usize::try_from(total).unwrap_or(usize::MAX))
}
}
pub trait FrameLength: Send + 'static {
const FIELD: LengthField;
}
pub struct LengthPrefixed<L: FrameLength> {
frame: Vec<u8>,
field: std::marker::PhantomData<fn() -> L>,
}
impl<L: FrameLength> LengthPrefixed<L> {
pub fn new(frame: impl Into<Vec<u8>>) -> Self {
LengthPrefixed {
frame: frame.into(),
field: std::marker::PhantomData,
}
}
pub fn frame(&self) -> &[u8] {
&self.frame
}
pub fn length_field(&self) -> u64 {
let f = L::FIELD;
let total = f
.frame_len(&self.frame)
.expect("frame shorter than its length field");
(total as i128 - i128::from(f.adjust)) as u64
}
pub fn into_frame(self) -> Vec<u8> {
self.frame
}
}
impl<L: FrameLength> Clone for LengthPrefixed<L> {
fn clone(&self) -> Self {
Self::new(self.frame.clone())
}
}
impl<L: FrameLength> PartialEq for LengthPrefixed<L> {
fn eq(&self, other: &Self) -> bool {
self.frame == other.frame
}
}
impl<L: FrameLength> Eq for LengthPrefixed<L> {}
impl<L: FrameLength> std::fmt::Debug for LengthPrefixed<L> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("LengthPrefixed").field(&self.frame).finish()
}
}
impl<L: FrameLength> Packet for LengthPrefixed<L> {
fn parse(buf: &mut Vec<u8>) -> Option<Self> {
let total = L::FIELD.frame_len(buf)?;
if buf.len() < total {
return None;
}
Some(Self::new(buf.drain(..total).collect::<Vec<u8>>()))
}
fn to_bytes(&self) -> Vec<u8> {
self.frame.clone()
}
}