Crate nuts_bytes

Source
Expand description

Conversion into a binary data format.

The nuts-bytes crate implements a tool that converts structured data into a binary format. See the Format specification section for a detailed description of the format.

§Deserialization from a binary representation

The deserialization describes the process of converting binary data into a data type that implements the FromBytes trait.

The Reader utility performs this deserialization by

  1. taking binary data from a source type that implements the TakeBytes trait and finally
  2. performs the deserialization.

The crate implements TakeBytes already for &[u8]. It takes bytes from a slice of u8 values.

§Deserialization example

use nuts_bytes::{Error, Reader, TakeBytesError};

// deserialize a primitive (u32)
let mut reader = Reader::new([0x00, 0x00, 0x02, 0x9A].as_slice());
let n: u32 = reader.read().unwrap();

assert_eq!(n, 666);

// Not enough data available
let mut reader = Reader::new([0; 3].as_slice());
let err = reader.read::<u32>().unwrap_err();

assert!(matches!(err, Error::TakeBytes(TakeBytesError::Eof)));

§Serialization into a binary representation

The serialization describes the process of converting a data type that implements the ToBytes trait into its binary representation.

The Writer utility performs this serialization. It

  1. performs the serialization and finally
  2. pushes the binary data into a target type, that implements the PutBytes trait.

The crate implements PutBytes for the following types:

§Serialization examples

§Serialize into a vec

use nuts_bytes::Writer;

// serialize a primitive (u32)
let mut writer = Writer::new(vec![]);
let n = writer.write(&666u32).unwrap();

assert_eq!(n, 4);
assert_eq!(writer.into_target(), [0x00, 0x00, 0x02, 0x9A]);

§Serialize into a slice

use nuts_bytes::Writer;

// serialize a primitive (u32)
let mut buf = [0; 4];
let mut writer = Writer::new(buf.as_mut_slice());
let n = writer.write(&666u32).unwrap();

assert_eq!(n, 4);
assert_eq!(buf, [0x00, 0x00, 0x02, 0x9A]);

// Not enough space for serialization
let mut buf = [0; 3];
let mut writer = Writer::new(buf.as_mut_slice());
let err = writer.write(&666u32).unwrap_err();

assert_eq!(format!("{}", err), "no more space available for writing");

§Format specification

The binary format is described here in detail.

Modules§

  • Derive macros available if nuts-bytes is built with features = ["derive"].
  • Documentation: format specification

Structs§

  • A cursor like utility that reads structured data from an arbitrary source.
  • A cursor like utility that writes structured data into an arbitrary target.

Enums§

Traits§

  • Trait that supports reading datatypes from a binary data stream.
  • Trait that describes a writer of binary data.
  • Trait that describes a reader of binary data.
  • Trait that supports writing datatypes into a binary data stream.

Derive Macros§