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
], [i64
], [String
], [Vec<T>
] and [HashMap<T, V>
].
Reading and writing of these types is done using the [byteorder
] crate.
Add the following to your Cargo.toml
file:
toml
[dependencies]
bytestream = "0.*"
You can find the documentation at: https://docs.rs/bytestream
```rust use std::io::{Cursor, Read, Result, Write}; use bytestream::*;
pub struct Foo { bar: String, baz: u32, }
impl Streamable for Foo {
fn readfrom
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::
// Write some data to the buffer let foo = Foo { bar: "corgi".toowned(), baz: 37 }; foo.writeto(&mut buffer, ByteOrder::BigEndian).unwrap();
// Read the data back from the buffer
// We wrap the buffer in a Cursor::Read
trait
let mut cursor = Cursor::new(buffer);
let other = Foo::read_from(&mut cursor, ByteOrder::BigEndian).unwrap();
assert_eq!(foo, other); ```
Streamable
support for std typesIf you do not wish to include out-of-the-box support for std types,
you can exclude the default batteries-included
feature in your
Cargo.toml
file:
toml
[dependencies]
bytestream = { Version = "0.*", default-features = false }
Exluding the batteries-included
feature will also remove
the byteorder
crate dependency.
The inspiration from this crate came from the [Stevenarella
] Minecraft client.