pub struct StreamDecoder<F> { /* private fields */ }Expand description
Stateful wrapper that drives a Framer over a growing input buffer.
It owns the Framer::next_frame_from progress hint, so a delimiter
search resumes where the previous call stopped. Use it whenever input
arrives in pieces (a socket read loop, a serial port, a message queue).
The input contract is the one described on Framer::next_frame_from:
between calls, only append to the buffer; after a frame is returned, drop
its consumed() bytes from the front.
§Example
use wire_codec::framing::{Delimited, StreamDecoder};
let mut decoder = StreamDecoder::new(Delimited::bounded(b"\n").unwrap());
let mut buffer: Vec<u8> = Vec::new();
let mut lines: Vec<Vec<u8>> = Vec::new();
for chunk in [&b"PI"[..], b"NG\nQU", b"IT\n"] {
buffer.extend_from_slice(chunk);
let mut start = 0;
while let Some(frame) = decoder.decode(&buffer[start..]).unwrap() {
lines.push(frame.payload().to_vec());
start += frame.consumed();
}
buffer.drain(..start);
}
assert_eq!(lines, [b"PING".to_vec(), b"QUIT".to_vec()]);Implementations§
Source§impl<F: Framer> StreamDecoder<F>
impl<F: Framer> StreamDecoder<F>
Sourcepub fn decode<'a>(&mut self, input: &'a [u8]) -> Result<Option<Frame<'a>>>
pub fn decode<'a>(&mut self, input: &'a [u8]) -> Result<Option<Frame<'a>>>
Try to extract the next frame from the start of input.
§Errors
Propagates the wrapped framer’s errors. The scan progress is cleared
on error, because the usual response (discarding the buffered input
and resynchronising) breaks the append-only contract the progress
hint relies on. Call StreamDecoder::reset yourself whenever you
discard or replace buffered input without an error.
Sourcepub fn reset(&mut self)
pub fn reset(&mut self)
Forget any partial-scan progress, for example after discarding the buffered input or switching to a new connection.
Sourcepub const fn framer(&self) -> &F
pub const fn framer(&self) -> &F
Borrow the wrapped framer, for example to call
Framer::write_frame on the outbound path.
Sourcepub fn into_inner(self) -> F
pub fn into_inner(self) -> F
Consume the decoder and return the wrapped framer.