bitrange
getting started
To get started, add this to your Cargo.toml
:
[]
= { = "https://github.com/trangar/bitrange" }
= { = "https://github.com/trangar/bitrange" }
Then add the following code to your main.rs
or lib.rs
extern crate bitrange;
extern crate bitrange_plugin;
bitrange needs a nightly version of the compiler because it uses the feature proc_macro
which is not stabilized yet
quoted strings
Because of an openstanding RFC 2320, stringify!
can not be used in a proc-macro attribute. The code generated by this crate contains:
where $format
and $struct_size_string
are from the bitrange
macro.
In this instance we'd like to use stringify!($format)
and stringify($struct_size_string)
, however this does not work until RFC 2320 lands.
For this reason, the format needs to be quoted, and we need to annotate the type twice. e.g.
bitrange!
instead of the desired
bitrange!
examples
Bitrange helps you map bit fields to proper getters and setters.
Say you're trying to make an IP parser. The rfc will give you this:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| IHL |Type of Service| Total Length |
If you wanted to parse this in Rust, you'd have to make the following mapping:
- the first 4 bits are mapped to
version
- The next 4 bits are mapped to
ihl
- The next 8 bits are mapped to
type_of_service
- The last 16 bits are mapped to
total_length
With bitrange, you can easily map bytes to fields. To parse this part of the protocol, simply write
extern crate bitrange;
bitrange!
If you wanted to make a field mutable, simply add a second ident to the field mapping, e.g.:
bitrange!
In addition, you can define constraints to bits that have to always be 0 or 1
bitrange!
Compile-time checks
bitrange will also check fields at compile time to see if they exist
bitrange!
However, this does not work for unmapped fields
bitrange!