Crate dgrambuf

source ·
Expand description

A fixed size ring buffer for datagrams of various sizes.

Implementation uses std::collections::VecDeque for metadata storage and a fixed size backing buffer for storage of datagram data.

Examples

Generic usage.

use dgrambuf::DatagramBuf;
use std::io::Write;

// allocate backing buffer
let mut dgram_buf = Vec::new();
dgram_buf.resize(128, 0);

// crate `DatagramBuf` based on preallocated buffer for datagram storage
let mut dgram_buf = DatagramBuf::from_slice(&mut dgram_buf);

// allocate new datagram slice within the backing store
let mut dgram = dgram_buf.alloc_front(50).unwrap();

// write to the buffer
write!(dgram, "hello world");
// truncate the buffer to the size of data written
dgram_buf.truncate_front("hello world".len());

// write another datagram
let mut dgram = dgram_buf.alloc_front(50).unwrap();
write!(dgram, "foo bar");
write!(dgram, " baz");
dgram_buf.truncate_front("foo bar baz".len());

// take oldest datagram form the buffer
let dgram = dgram_buf.pop_back().unwrap();
assert_eq!(dgram, b"hello world");

let dgram = dgram_buf.pop_back().unwrap();
assert_eq!(dgram, b"foo bar baz");

Usage as store and forward buffer for UNIX datagram socket.

use dgrambuf::DatagramBuf;
use std::os::unix::net::UnixDatagram;

fn main() -> std::io::Result<()> {
    let socket = UnixDatagram::bind("/path/to/my/socket")?;

    // allocate backing buffer
    let mut dgram_buf = Vec::new();
    dgram_buf.resize(512, 0);

    let mut dgram_buf = DatagramBuf::from_slice(&mut dgram_buf);

    // receive 10 datagrams up to 128 bytes in length each
    for _ in 0..10 {
        // drop old datagrams if there is not enough space left in the backing buffer (512)
        let mut buf = dgram_buf.alloc_front_drop(128).unwrap();

        let count = socket.recv(&mut buf)?;
        // reduce the size of the allocation to fit the datagram received
        dgram_buf.truncate_front(count);
    }

    // send back the received datagrams in order
    while let Some(mut buf) = dgram_buf.pop_back() {
        socket.send(&mut buf)?;
    }
    Ok(())
}

Structs

A fixed size ring buffer for datagrams of various sizes.

Traits

Types that can be used as data buffer.