Crates.io | structure |
lib.rs | structure |
version | 0.1.2 |
source | src |
created_at | 2017-06-10 11:46:47.160979 |
updated_at | 2018-01-11 23:07:59.896957 |
description | Use format strings to create strongly-typed data pack/unpack interfaces. |
homepage | https://github.com/liranringel/structure |
repository | https://github.com/liranringel/structure |
max_upload_size | |
id | 18434 |
size | 21,161 |
Use format strings to create strongly-typed data pack/unpack interfaces (inspired by Python's struct
library).
Add this to your Cargo.toml
:
[dependencies]
structure = "0.1"
And this to your crate root:
#[macro_use]
extern crate structure;
// Two `u32` and one `u8`
let s = structure!("2IB");
let buf: Vec<u8> = s.pack(1, 2, 3)?;
assert_eq!(buf, vec![0, 0, 0, 1, 0, 0, 0, 2, 3]);
assert_eq!(s.unpack(buf)?, (1, 2, 3));
It's useful to use pack_into
and unpack_from
when using types that implement Write
or Read
.
The following example shows how to send a u32
and a u8
through sockets:
use std::net::{TcpListener, TcpStream};
let listener = TcpListener::bind("127.0.0.1:0")?;
let mut client = TcpStream::connect(listener.local_addr()?)?;
let (mut server, _) = listener.accept()?;
let s = structure!("IB");
s.pack_into(&mut client, 1u32, 2u8)?;
let (n, n2) = s.unpack_from(&mut server)?;
assert_eq!((n, n2), (1u32, 2u8));
Licensed under either of
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.