pub struct TcpFrameDecoder { /* private fields */ }Expand description
A stateful decoder for RFC 4571 framed TCP packets.
This decoder buffers incoming TCP data and extracts complete framed packets. It handles partial reads gracefully - you can feed it data in any chunk size.
Input from a peer is bounded: push refuses data that would take the buffer
past its limit (DEFAULT_MAX_BUFFERED, or with_max_buffered),
so a peer that sends faster than the reader takes packets cannot grow it without limit.
Taking a packet is amortised O(1) in the buffered length: the consumed prefix is compacted
away only once it outweighs what is left, rather than shifted out after every packet.
§Example
use rtci_shared::tcp_framing::TcpFrameDecoder;
let mut decoder = TcpFrameDecoder::new();
// Simulate receiving data in chunks
let chunk1 = &[0, 5, b'H', b'e']; // Partial: header + 2 bytes
let chunk2 = &[b'l', b'l', b'o']; // Remaining 3 bytes
decoder.extend_from_slice(chunk1);
assert!(decoder.next_packet().is_none()); // Not complete yet
decoder.extend_from_slice(chunk2);
assert_eq!(decoder.next_packet(), Some(b"Hello".to_vec()));Implementations§
Source§impl TcpFrameDecoder
impl TcpFrameDecoder
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a new decoder with pre-allocated buffer capacity.
Sourcepub fn with_max_buffered(self, max_buffered: usize) -> Self
pub fn with_max_buffered(self, max_buffered: usize) -> Self
Sets how many unconsumed bytes push lets the decoder hold. At least one
whole frame is always allowed, so every valid frame can complete.
Sourcepub fn extend_from_slice(&mut self, data: &[u8])
pub fn extend_from_slice(&mut self, data: &[u8])
Appends data to the internal buffer, without a limit. For data from a peer, use
push.
Sourcepub fn push(&mut self, data: &[u8]) -> Result<()>
pub fn push(&mut self, data: &[u8]) -> Result<()>
Appends data from a peer, refusing it (and buffering none of it) when the unconsumed bytes would exceed the limit: the reader is not keeping up, or the peer is flooding. A refusal leaves the stream’s framing unknowable, so the connection should be closed.
§Errors
Error::ErrBufferFull when the data does not fit.
§Example
use rtci_shared::tcp_framing::{TcpFrameDecoder, DEFAULT_MAX_BUFFERED};
let mut decoder = TcpFrameDecoder::new();
assert!(decoder.push(&[0, 1, 7]).is_ok());
assert!(decoder.push(&vec![0; DEFAULT_MAX_BUFFERED]).is_err());
assert_eq!(decoder.next_packet(), Some(vec![7]));Sourcepub fn next_packet(&mut self) -> Option<Vec<u8>>
pub fn next_packet(&mut self) -> Option<Vec<u8>>
Attempts to extract the next complete packet from the buffer.
Returns Some(packet) if a complete packet is available,
or None if more data is needed.
The returned packet does not include the 2-byte length header.
Sourcepub fn buffered_len(&self) -> usize
pub fn buffered_len(&self) -> usize
Returns the number of buffered bytes.