Skip to main content

wire_codec/framing/
mod.rs

1//! Frame extraction strategies.
2//!
3//! A [`Framer`] is a stateless protocol that locates and emits one frame at a
4//! time from a borrowed byte slice. Frames are described by [`Frame`], which
5//! carries a zero-copy reference to the payload alongside the count of bytes
6//! the framer consumed from the input.
7//!
8//! Two concrete framers ship with the crate:
9//!
10//! - [`length::LengthPrefixed`] for fixed-width length-prefixed protocols.
11//! - [`delimiter::Delimited`] for byte-delimited protocols such as newline-
12//!   terminated text.
13//!
14//! Custom framers are implemented by writing a `Framer` impl on a user-defined
15//! type.
16
17pub mod delimiter;
18pub mod length;
19
20pub use delimiter::Delimited;
21pub use length::{Endian, LengthPrefixed, LengthWidth};
22
23use crate::buf::WriteBuf;
24use crate::error::Result;
25
26/// A frame extracted from an input byte slice.
27///
28/// The `payload` borrow lives as long as the input slice, so framers never
29/// copy data. `consumed` tells the caller how many bytes from the input the
30/// frame occupied in total, including any header or delimiter bytes.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Frame<'a> {
33    payload: &'a [u8],
34    consumed: usize,
35}
36
37impl<'a> Frame<'a> {
38    /// Construct a frame from its payload and total consumed-byte count.
39    ///
40    /// `consumed` must be at least `payload.len()`; framers in this crate
41    /// uphold that invariant.
42    #[inline]
43    pub const fn new(payload: &'a [u8], consumed: usize) -> Self {
44        Self { payload, consumed }
45    }
46
47    /// Zero-copy borrow of the frame payload.
48    #[inline]
49    pub const fn payload(&self) -> &'a [u8] {
50        self.payload
51    }
52
53    /// Number of bytes the framer consumed from the input to produce this frame.
54    #[inline]
55    pub const fn consumed(&self) -> usize {
56        self.consumed
57    }
58}
59
60/// Strategy that extracts and emits one frame at a time.
61///
62/// Implementations are stateless: each call to [`Framer::next_frame`] is
63/// independent. To process a stream, the caller advances their own read
64/// position by [`Frame::consumed`] after each successful call.
65///
66/// # Example
67///
68/// ```
69/// use wire_codec::framing::{Framer, LengthPrefixed, LengthWidth, Endian};
70///
71/// let framer = LengthPrefixed::new(LengthWidth::U16, Endian::Big);
72/// let input = &[0x00, 0x03, b'h', b'i', b'!'];
73/// let frame = framer.next_frame(input).unwrap().unwrap();
74/// assert_eq!(frame.payload(), b"hi!");
75/// assert_eq!(frame.consumed(), 5);
76/// ```
77pub trait Framer {
78    /// Try to extract a single frame from the start of `input`.
79    ///
80    /// Returns `Ok(Some(frame))` when a complete frame is available,
81    /// `Ok(None)` when more bytes are needed, and `Err(_)` when the input
82    /// violates the protocol.
83    ///
84    /// # Errors
85    ///
86    /// Implementation-defined; see each concrete framer for its error contract.
87    fn next_frame<'a>(&self, input: &'a [u8]) -> Result<Option<Frame<'a>>>;
88
89    /// Serialize `payload` as a single frame into `out`.
90    ///
91    /// # Errors
92    ///
93    /// Implementation-defined; see each concrete framer.
94    fn write_frame(&self, payload: &[u8], out: &mut WriteBuf<'_>) -> Result<()>;
95}