pktbuilder 0.1.0

Safe builder for building packets
Documentation
  • Coverage
  • 95.92%
    47 out of 49 items documented1 out of 47 items with examples
  • Size
  • Source code size: 36.95 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.53 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 6s Average build duration of successful builds.
  • all releases: 9s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • sensorfu/pktbuilder
    1 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • oherrala

pktbuilder

A safe builder for building network packets.

A simple way to build packets is to give a buffer to [Builder] and use it's methods to populate buffer with values.

use std::net::Ipv4Addr;
use pktbuilder::Builder;

fn example1() -> Result<(), pktbuilder::Error> {
    let mut buffer = [0u8; 6];
    let mut builder = Builder::new(&mut buffer);

    let ip = Ipv4Addr::new(192, 0, 2, 42);

    builder
        .add_byte(0x01)?
        .add_ipv4_address_be(ip)?
        .add_byte(0x02)?;

    assert_eq!(buffer, [0x01_u8, 192, 0, 2, 42, 0x02]);
    Ok(())
}

But for most cases we already have e.g. a struct that should be encoded so we can implement [Buildable] trait for the struct and use [Buildable::build] method to write into [Builder]:

use std::net::Ipv4Addr;
use pktbuilder::{Builder, Buildable};

struct Foo {
    foo: u8,
    ip: Ipv4Addr,
    bar: u8,
}

impl Buildable for Foo {
    fn build(&self, builder: &mut Builder<'_>) -> Result<(), pktbuilder::Error> {
        builder
            .add_byte(self.foo)?
            .add_ipv4_address_be(self.ip)?
            .add_byte(self.bar)?;
        Ok(())
    }
}


fn example2() -> Result<(), pktbuilder::Error> {
    let mut buffer = [0u8; 6];
    let mut builder = Builder::new(&mut buffer);

    let foo = Foo {
        foo: 0x01,
        ip: Ipv4Addr::new(192, 0, 2, 42),
        bar: 0x02,
    };

    foo.build(&mut builder)?;

    assert_eq!(buffer, [0x01_u8, 192, 0, 2, 42, 0x02]);
    Ok(())
}