#buffer #byte-buffer #byte #type #no-alloc

no-std tbytes

A tiny library for reading and writing typed data into buffers

3 releases

0.1.0 Mar 25, 2024
0.1.0-alpha2 Dec 7, 2023

#770 in Data structures

Download history 11/week @ 2024-03-11 151/week @ 2024-03-18 240/week @ 2024-03-25 67/week @ 2024-04-01 49/week @ 2024-04-08 23/week @ 2024-04-15 22/week @ 2024-04-22 13/week @ 2024-04-29 3/week @ 2024-05-06 18/week @ 2024-05-13 23/week @ 2024-05-20 32/week @ 2024-05-27 25/week @ 2024-06-03 21/week @ 2024-06-10 20/week @ 2024-06-17 17/week @ 2024-06-24

86 downloads per month
Used in 4 crates (2 directly)

MIT/Apache

45KB
315 lines

T-Bytes

logo

T-Bytes is a tiny library for reading and writing typed data into bytes buffers. It is designed mainly for no-std, no-alloc targets or crates which consider to support no-std.

Documentation can be found here.

Installation

cargo add tbytes

Usage

It would be easier to start from an example. Here we create a buffer and populate it with heterogeneous values.

use tbytes::errors::TBytesError;
use tbytes::{BytesWriterFor, TBytesReader, TBytesReaderFor, TBytesWriter};

fn main() -> Result<(), TBytesError> {
    type Content = (i16, f32, [u8; 2], [i16; 2]);
    let mut buffer = [0u8; 12];
    
    let mut writer = TBytesWriter::from(buffer.as_mut_slice());
    
    let into_values: Content = (-1048, 0.32, [10, 31], [-1, 240]);
    writer.write(into_values.0)?;
    writer.write(into_values.1)?;
    writer.write_slice(into_values.2.as_slice())?;
    writer.write_array(into_values.3)?;
    
    assert!(matches!(writer.write(0u8), Err(TBytesError::OutOfBounds)));
    
    let reader = TBytesReader::from(buffer.as_slice());
    
    let mut from_values: Content = Content::default();
    from_values.0 = reader.read()?;
    from_values.1 = reader.read()?;
    from_values.2 = reader.read_array()?;
    from_values.3 = reader.read_array()?;
    
    assert!(matches!(
          reader.read() as Result<u8, TBytesError>,
          Err(TBytesError::OutOfBounds)
      ));
    
    assert_eq!(into_values, from_values);
    
    Ok(())
}

See examples for advanced usage.

Examples

  • basic — basic read/write.
    cargo run --example basic
    

Limitations

We want to keep as simple as possible but simplicity comes with a price.

  • At the moment only little endian is supported.
  • We currently supports only numeric types and arrays of such types. But you can always implement your own TBytesReaderFor / TBytesWriterFor. Or even better, submit a pull request!

License

Here we simply comply with the suggested dual licensing according to Rust API Guidelines (C-PERMISSIVE).

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~175KB