Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/techassi/binbuf
A small library to work with binary (network) data in Rust
https://github.com/techassi/binbuf
binary rust rust-crate rust-library
Last synced: 2 days ago
JSON representation
A small library to work with binary (network) data in Rust
- Host: GitHub
- URL: https://github.com/techassi/binbuf
- Owner: Techassi
- License: mit
- Created: 2022-09-20T13:32:23.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-08-04T17:16:46.000Z (3 months ago)
- Last Synced: 2024-08-04T19:18:12.914Z (3 months ago)
- Topics: binary, rust, rust-crate, rust-library
- Language: Rust
- Homepage:
- Size: 213 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# binbuf
binbuf (short for *binary buffers*) is a small library to work with binary (network) data in Rust. Just add
`binbuf::prelude::*` to your imports. This imports the most important parts of the library.## Reading from `Reader`
### Reading basic types
The library provides multiple methods to read basic data types like `u8`, `u16`, `u32`, `u64`, `u128`,
`Ipv4Addr`, and `Ipv6Addr` in big and little-endian byte order.```rust
let b = vec![69, 88, 65, 77, 80, 76, 69, 33];
let mut b = Reader::new(b.as_slice());match u16::read::(&mut b) {
Ok(n) => assert_eq!(n, 17752),
Err(err) => panic!("{}", err),
}
```### Reading structs and enums
To read custom data structs or enums, we can use the derive macro `#[derive(Read)]` to annotate the structs.
```rust
#[derive(Read)]
struct Data {
inner: u16,
}let b = vec![69, 88, 65, 77, 80, 76, 69, 33];
let mut buf = Reader::new(b.as_slice());match Data::read::(&mut buf) {
Ok(data) => assert_eq!(data.inner, 17752),
Err(err) => panic!("{}", err)
}
```Customize the derive macro by annotating the struct with additional attributes: `#[binbuf()]`. Currently, the following
container attributes are supported:- `#[binbuf(error = "...")]`
> Default value: `binbuf::error::BufferError`
Provide a custom error. The error has to implement these traits:
- `std::fmt::Display`
- `std::error::Error`
- `From`- `#[binbuf(endianness = "...")]`
> Default value: `both`
Specify the supported endianness for the `ReadableVerify` trait. Possible values are:
- `little`
- `both`
- `big`Enums can be tagged with one additional attribute:
- `#[binbuf(repr = "...")]`
> Default value: `u8`
The library works well with the `thiserror` crate. Implementing custom errors with the `Error` derive macro is
straightforward:```rust
use thiserror::Error;#[derive(Error)]
enum CustomError {
#[error("Invalid data")]
Invalid,#[error("Buffer error: {0}")]
BufferError(#[from] BufferError)
}
```