The main goal of this crate is to simplify serialization of type's and structures to bytes.
If one works with binary formats/protocols a lot of time is spent implementing decoding and encoding types and structures of the format/protocol in order to further process the contained data.
For decoding parsers generators like nom are very helpful and easy the implmentation. This create tries to provide a lightweight encoding/output conbinator by just introducing 2 new traits which in turn then can make use of the iterator facilites to crate the desired output chain of bytes.
By introducing such a trait complex (compsites) structures in a lot of cases can be implemented by just encoding and chaining the childs in order
The fileds of a type still can be used for encoding but there is no hard dependency on their order nor their actual size
e.g. a protocol field size with the encoded size of 2 Bytes (u16), still can be represented e.g. as usize withn the structures/type which save quite some converting and casting.
There is no need of a type to provide a specific amount of memory in order to be serialized (the serialization of a type or a type could be 100% computational)
e.g.: assume this protocol type/structure (Packet)
shell
+-----------------+-------------------+-----------------+
| field1 (1 Byte) | reserved (7 Byte) | filed2 (8 Byte) |
+-----------------+-------------------+-----------------+
internally it could be represented and implemented like this
```rust use tobytes::ByteView; use tobytes::ToBytes;
struct Packet { field1: u8, field2: u64 }
impl Packet { const RESERVED : u8 = 0x00; }
impl ByteView for Packet {
fn byteat(&self, index: usize) -> Option
}
else {
None
}
}
fn bytesize(&self) -> usize { ByteView::bytesize(&self.field1) + 7usize + ByteView::byte_size(&self.field2) } }
let field1 = 0xaau8; let field2 = 0xaabbccddeeff11u64.tobe(); let p = Packet {field1, field2}; let mut bytes = p.tobytes();
asserteq!(16usize, p.bytesize());
assert_eq!(
vec![0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11],
bytes.collect::
```rust use tobytes::ByteView; use tobytes::ToBytes;
let uint16be : u16 = 0x0A0Bu16.tobe(); let uint16le : u16 = 0x0C0Du16.tole(); let uint32le : u32 = 0x01020304u32.tole();
let uint16bebytes = uint16be.tobytes(); let uint16lebytes = uint16le.tobytes(); let uint32lebytes = uint32le.tobytes();
let mut bytes = uint16bebytes.chain(uint16lebytes.chain(uint32lebytes));
assert_eq!(vec![0x0A, 0x0B, 0x0D, 0x0C, 0x04, 0x03, 0x02, 0x01], bytes.collect::
TBD
TBD