databuf-0.2.0 has been yanked.
This library used to serialize and deserialize structured data in binary format.
Examples
[]
= "0.2"
use ;
let old = Company ;
let bytes = old.;
let new = .unwrap;
- Zero-copy deserialization: mean that no data is copied.
Vec,String,&[T],&stretc.. are encoded with their length value first, Following by each entry.
use ;
let bytes = ;
// ^^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Id Len Data
let msg = .unwrap;
assert_eq!;
assert_eq!; // Here, data is referenced.
- Example: Encoding data into a buffer of specified size.
use ;
/// Use big endian byte order + Encode `msg` length with `databuf::var_int::LEU15`
const CONFIG: u8 = BE | LEU15;
let record = Record ;
let mut buf = ;
let remaining = &mut buf.as_mut_slice;
record..unwrap;
let amt = 20 - remaining.len;
assert_eq!; // 15 bytes written to `buf`
Variable-Length Integer Encoding
This encoding ensures that smaller integer values need fewer bytes to encode. Support types are LEU15, LEU22, LEU29, Encoded in little endian.
By default, LEU29 is used to encode length.
Encoding algorithm is very straightforward, The most significant bits of the first byte determine the byte length to encode the number in little endian.
LEU15
| MSB | Length | Usable Bits | Range |
|---|---|---|---|
| 0 | 1 | 7 | 0..128 |
| 1 | 2 | 15 | 0..32768 |
LEU22
| MSB | Length | Usable Bits | Range |
|---|---|---|---|
| 0 | 1 | 7 | 0..128 |
| 10 | 2 | 14 | 0..16384 |
| 11 | 3 | 22 | 0..4194304 |
LEU29
| MSB | Length | Usable Bits | Range |
|---|---|---|---|
| 0 | 1 | 7 | 0..128 |
| 10 | 2 | 14 | 0..16384 |
| 110 | 3 | 21 | 0..2097152 |
| 111 | 4 | 29 | 0..536870912 |
For example, Binary representation of 0x_C0DE is 0x_11_00000011_011110
LEU22(0x_C0DE) is encoded in 3 bytes:
1st byte: 11_011110 # MSB is 11, so read next 2 bytes
2nd byte: 11
3rd byte: 11
Another example, LEU22(107) is encoded in just 1 byte:
1st byte: 0_1101011 # MSB is 0, So we don't have to read extra bytes.