Skip to main content

Crate packetwire

Crate packetwire 

Source
Expand description

§packetwire

Crates.io Documentation License

packetwire is a bounded, deterministic binary codec for small packet protocols. It provides stable packet IDs, derive-based payload encoding, and framing for both byte streams and datagrams without unsafe code.

§Installation

Add the crate to your project:

[dependencies]
packetwire = "0.1"

The #[packet] and #[packet_set] macros are re-exported by packetwire; a separate dependency on packetwire-derive is not required.

§Quick start

Declare packet structs with stable IDs and collect them in a dispatch enum:

use packetwire::{PacketDecoder, PacketEncoder, packet, packet_set};

#[packet(id = 1)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct Ping {
    sequence: u32,
}

#[packet(id = 2)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct Pong {
    sequence: u32,
}

#[packet_set]
#[derive(Debug, Clone, PartialEq, Eq)]
enum Message {
    Ping(Ping),
    Pong(Pong),
}

fn main() -> packetwire::Result<()> {
    let frame = PacketEncoder::default().encode(&Ping { sequence: 7 })?;
    let message = PacketDecoder::<Message>::default().decode_datagram(&frame)?;
    assert_eq!(message, Message::Ping(Ping { sequence: 7 }));
    Ok(())
}

Fields are encoded in declaration order. Once a protocol is published, packet IDs and field order should be treated as part of its stable wire contract.

§Streams and datagrams

For UDP and other message-oriented transports, place exactly one Packetwire frame in each datagram and decode it with decode_datagram. Empty, truncated, multi-frame, and trailing-byte datagrams are rejected.

For TCP, QUIC streams, and other byte streams, retain one decoder per stream. Feed every received chunk into it and drain all complete packets before reading more data:

fn decode_stream(chunks: &[&[u8]]) -> packetwire::Result<Vec<Message>> {
    let mut decoder = PacketDecoder::<Message>::default();
    let mut messages = Vec::new();

    for chunk in chunks {
        decoder.push(chunk)?;
        while let Some(message) = decoder.try_decode()? {
            messages.push(message);
        }
    }

    decoder.finish()?;
    Ok(messages)
}

finish reports an incomplete final frame after the transport reaches EOF. Malformed frame headers should normally cause the stream to be closed.

§Wire format

Every frame contains:

canonical variable-integer body length
canonical variable-integer packet ID
packet payload fields in declaration order
  • Packet IDs are stable 16-bit values.
  • Frame and collection lengths use canonical QUIC-style variable integers.
  • Fixed-width integers and floating-point bit patterns use big-endian order.
  • Strings are length-prefixed UTF-8.
  • Booleans accept only the bytes 0 and 1.
  • Collections, arrays, options, boxed values, and unit values have built-in codecs.

Custom field types can implement BinaryEncode and BinaryDecode directly.

§Resource limits

Encoding and decoding are bounded through CodecConfig and DecodeLimits. The default configuration permits 1 MiB frame bodies, retains at most 2 MiB of unread stream data, and limits individual strings and collections to 256 KiB or 256K elements respectively.

Applications handling untrusted input should choose limits appropriate for their protocol. Limit failures, malformed values, unknown packet IDs, trailing payloads, and incomplete frames are returned as ProtocolError values.

§Networking examples

The repository includes continuous loopback client/server examples for UDP, TCP, and QUIC. Each runs until Ctrl-C, then exchanges a protocol-level stream end packet and shuts down cleanly:

cargo run --example udp
cargo run --example tcp
cargo run --example quic

The QUIC example uses Quinn and a temporary self-signed certificate generated at startup. Networking libraries used by the examples are development dependencies and are not part of packetwire’s runtime dependency surface.

§Minimum supported Rust version

packetwire requires Rust 1.85 or newer and uses the Rust 2024 edition.

§Development

Run the complete workspace checks with:

cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --all-targets
cargo test --workspace --doc

Generate the coverage report with:

rustup component add llvm-tools-preview
cargo install cargo-llvm-cov --version 0.8.7 --locked
./scripts/coverage.sh

Coverage fails unless every production line, function, and region in both workspace crates is exercised. LLVM branch coverage is included in the report.

§License

MIT

Structs§

BinaryReader
A cursor over one bounded packet payload.
BinaryWriter
A bounded, append-only encoder for packet payload fields.
CodecConfig
Resource limits shared by packet encoders and decoders.
DecodeLimits
Allocation limits applied while decoding length-prefixed payload values.
PacketDecoder
Incremental decoder for a reliable byte stream.
PacketEncoder
Encodes concrete packets or packet-set enum values into complete frames.
PacketId
Stable 16-bit identifier stored at the start of every packet frame body.

Enums§

ProtocolError
A malformed value, invalid frame, unknown packet, or configured limit violation encountered by the protocol codec.

Constants§

PROTOCOL_VERSION
The application protocol version represented by this codec.

Traits§

BinaryDecode
Constructs a value from the deterministic Packetwire binary representation.
BinaryEncode
Encodes a value into the deterministic Packetwire binary representation.
Packet
A concrete packet type with a stable wire ID.
PacketEncode
A value that can be framed by PacketEncoder.
PacketSet
Dispatches a packet payload after the frame decoder has read its ID.

Type Aliases§

Result
Result type returned by protocol encoding and decoding operations.

Attribute Macros§

packet
Implements binary encoding, binary decoding, and a stable packet ID for a named, tuple, unit, or generic struct.
packet_set
Turns a non-empty enum of single-field tuple variants into an ID-dispatching packet set.