Skip to main content

Module codec

Module codec 

Source
Available on crate feature bytes only.
Expand description

Adapters that run a Framer over a growable bytes::BytesMut buffer.

Available with the bytes feature. FrameCodec wraps any framer and exposes two inherent methods, FrameCodec::decode_frame and FrameCodec::encode_frame, that work on BytesMut directly. The tokio-util and asynchronous-codec features add implementations of those crates’ Decoder and Encoder traits on top, so a framer plugs straight into tokio_util::codec::Framed or asynchronous_codec::Framed:

ⓘ
use tokio_util::codec::Framed;
use wire_codec::codec::FrameCodec;
use wire_codec::framing::{Endian, LengthPrefixed, LengthWidth};

let codec = FrameCodec::new(LengthPrefixed::bounded(LengthWidth::U32, Endian::Big));
let mut framed = Framed::new(tcp_stream, codec);
// framed: Stream<Item = io::Result<BytesMut>> + Sink<&[u8]>

Decoded payloads are split off the receive buffer without copying when the framer returns a payload that lies inside the frame (all built-in framers do). The decoder keeps the resumable-scan state described on Framer::next_frame_from, so a slow peer cannot force quadratic work.

The trait implementations use std::io::Error as their error type, like tokio-util’s own codecs; the original Error is available through io::Error::get_ref and downcast_ref.

Structs§

FrameCodec
A Framer driven over a BytesMut buffer.