This library used to serialize and deserialize structured data in binary format.
Endianness
By default, the library uses little endian.
If you want to use big endian, you can set BE features flag. And for native endian use NE. For example:
[]
= { = "0.1", = ["BE"] }
Examples
use *;
let old = Company ;
let bytes = old.encode;
let new = decode;
- Zero-copy deserialization: mean that no data is copied. Dynamic length data (
Vec,String,&[T],&stretc..) are encoded with their length value first, Following by each entry.
use *;
let bytes = ;
// ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Id Len Data
let msg = decode.unwrap;
assert_eq!;
assert_eq!; // Here, data is referenced.
- In this example, The following structs, don't have any dynamic length data. So we can have a fixed size buffer at compile time.
use *;
let record = Record ;
let mut writer = ;
record.encoder;
- It's very easy to implement
EncoderorDecodertrait. For example:
use io;
use *;
type DynErr = ;
;
Variable-Length Integer Encoding
This encoding ensures that smaller integer values need fewer bytes to encode. Support types are L2 and L3, both are encoded in little endian.
By default, L3 (u22) is used to encode length (integer) for record. But you override it by setting L2 (u15) in features flag.
Encoding algorithm is very straightforward, reserving one or two most significant bits of the first byte to encode rest of the length.
L2
| MSB | Length | Usable Bits | Range |
|---|---|---|---|
| 0 | 1 | 7 | 0..128 |
| 1 | 2 | 15 | 0..32768 |
L3
| MSB | Length | Usable Bits | Range |
|---|---|---|---|
| 0 | 1 | 7 | 0..128 |
| 10 | 2 | 14 | 0..16384 |
| 11 | 3 | 22 | 0..4194304 |
For example, Binary representation of 0x_C0DE is 0x_11_00000011_011110
L3(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, L3(107) is encoded in just 1 byte:
1st byte: 0_1101011 # MSB is 0, So we don't have to read extra bytes.
Fixed-Length Collections
Record can be used to encode collections where the size of the length is known.
For example, Record<u8, String> here the maximum allowed payload length is 255 (u8::MAX)