packetwire 0.1.0

Bounded deterministic binary packet codec with stream and datagram framing
Documentation

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:

# use packetwire::{PacketDecoder, packet, packet_set};
# #[packet(id = 1)]
# struct Ping { sequence: u32 }
# #[packet_set]
# enum Message { Ping(Ping) }
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