bitwrap
Intro
bitwrap is a derive macro and trait to declare a struct data member with explicit size, in bits.
Bitfield
bits attribute accept only one argument - field size in bits.
For example packet has next format:
| Field | Bits |
|---|---|
| flag_1 | 1 |
| flag_2 | 1 |
| data_3 | 2 |
| data_4 | 12 |
use *;
const DATA: & = &;
let mut packet = default;
packet.unpack.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
let mut buffer: = ;
let result = packet.pack.unwrap;
assert_eq!;
assert_eq!;
Skip bits
Some packets contains reserved or fixed bits.
This bits could be skiped with bits_skip attribute.
For example packet has next format:
| Field | Bits |
|---|---|
| Data | 6 |
| 0b00 | 2 |
| 0b1111 | 4 |
| Data | 4 |
bits_skip attribute accept next arguments:
- size in bits
- value. optional argument. by the default: 0
use *;
const DATA: & = &;
let mut packet = default;
packet.unpack.unwrap;
assert_eq!;
assert_eq!;
let mut buffer: = Vecnew;
buffer.resize;
let result = packet.pack.unwrap;
assert_eq!;
Nested objects
Nested field is an object with BitWrap interface.
For example part of IPv4 packet:
| Field | Bits |
|---|---|
| ttl | 8 |
| protocol | 8 |
| checksum | 16 |
| src | 32 |
| dst | 32 |
use Ipv4Addr;
use *;
const DATA: & = &;
let mut packet = IP4 ;
packet.unpack.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
let mut buffer: = Vecnew;
buffer.resize;
let result = packet.pack.unwrap;
assert_eq!;
Types converter
This feature converts numerical type into the field type. Here is numerical type means an unsigned number that enough to contain all data. Field type means a type of the struct field.
For example bits(1) - numerical type will be u8.
If the field type is bool then conversion code will be appended automatically.
For other types or for value conversion you may use - bits_convert(1, from, into):
from- method to convert field type from numeric typeinto- method to convert numeric type into field type
If conversion methods not defined - bits_convert(1) will be used
From and Into traits implemented for the field type.
| Field | Bits |
|---|---|
| Reserved | 4 |
| Coffee | 4 |
const DATA: & = &;
let mut packet = default;
packet.unpack.unwrap;
assert_eq!;
let mut buffer: = ;
let result = packet.pack.unwrap;
assert_eq!;