#binary-data #byte-buffer #read-write #binary #byte #read #write

bytestream

Provides a convenient way of writing binary data to a buffer

5 releases (3 breaking)

0.4.1 Feb 3, 2021
0.4.0 Feb 3, 2021
0.3.0 Jun 17, 2020
0.2.0 Jun 17, 2020
0.1.0 Jun 16, 2020

#1400 in Encoding

Download history 162/week @ 2023-12-12 178/week @ 2023-12-19 69/week @ 2023-12-26 440/week @ 2024-01-02 350/week @ 2024-01-09 278/week @ 2024-01-16 1380/week @ 2024-01-23 313/week @ 2024-01-30 381/week @ 2024-02-06 464/week @ 2024-02-13 572/week @ 2024-02-20 554/week @ 2024-02-27 1459/week @ 2024-03-05 621/week @ 2024-03-12 326/week @ 2024-03-19 438/week @ 2024-03-26

2,908 downloads per month
Used in 8 crates (7 directly)

MIT license

20KB
245 lines

This crate provides a convenient way of reading and writing bytes to a buffer that implements the standard Read or Write traits.

Supported std types include u8, u16, u32, u64, i8, i16, i32 and i64.

Reading and writing of these types is done using the byteorder crate.

Installation

Add the following to your Cargo.toml file:

[dependencies]
bytestream = "0.4"

Examples

use std::io::{Cursor, Read, Result, Write};
use bytestream::*;

#[derive(Debug, PartialEq)]
pub struct Foo {
    bar: bool,
    baz: u32,
}

impl StreamReader for Foo {
    fn read_from<R: Read>(buffer: &mut R, order: ByteOrder) -> Result<Self> {
        Ok(Self {
            bar: bool::read_from(buffer, order)?,
            baz: u32::read_from(buffer, order)?,
        })
    }
}

impl StreamWriter for Foo {
    fn write_to<W: Write>(&self, buffer: &mut W, order: ByteOrder) -> Result<()> {
        self.bar.write_to(buffer, order)?;
        self.baz.write_to(buffer, order)?;
        Ok(())
    }
}

// Create a buffer that implements the `Write` trait
let mut buffer = Vec::<u8>::new();

// Write some data to the buffer
let foo = Foo { bar: true, baz: 37 };
foo.write_to(&mut buffer, ByteOrder::BigEndian).unwrap();

// Read the data back from the buffer
// We wrap the buffer in a Cursor::<T> that implements the `Read` trait
let mut cursor = Cursor::new(buffer);
let other = Foo::read_from(&mut cursor, ByteOrder::BigEndian).unwrap();

assert_eq!(foo, other);

Exclude streamable support for std types

If you do not wish to include out-of-the-box support for std types, you can exclude the default feature in your Cargo.toml file:

[dependencies]
bytestream = { Version = "0.4", default-features = false }

Exluding the default feature will also remove the byteorder crate dependency.

Credits

The inspiration from this crate came from the Stevenarella Minecraft client.

Dependencies

~120KB