bseq!() { /* proc-macro */ }Expand description
bseq is a procedural macro for creating bit sequences.
This macro enables the generation of bit sequences using a simple syntax. Bit sequences can be specified directly, through hex values, or by using identifiers or integers each with a specific length. This proves especially useful in systems programming and when interacting with low-level hardware or protocols where bit manipulation is a common requirement.
§Examples
§Direct raw bit sequence:
use bit_seq::bseq;
let t = bseq!(0110 01 0 1);
assert_eq!(t, 0b0110_01_0_1);§Using hex values:
Hex values conveniently add 4 bits per hexadecimal place.
use bit_seq::bseq;
let t = bseq!(01 0x1f);
assert_eq!(t, 0b01_0001_1111);§Using value length expression:
Employ the format <val>:<len> where len specifies how many of the
least significant bits from val should be used.
use bit_seq::bseq;
let t = bseq!(3:1 0 0xf:2);
assert_eq!(t, 0b1_0_11);§Using variable length expression:
It is also possible to interpolate outer variables for length expressions.
use bit_seq::bseq;
let var = 0xf;
let t = bseq!(10 var:2);
assert_eq!(t, 0b10_11);§Unary Operations
The bseq syntax supports unary operations for length expressions. This simplifies bit sequences like
0b111111.
use bit_seq::bseq;
// bit negation
assert_eq!(bseq!(!0:6), 0b111111);
// numerical negation with variable interpolation
let var = 1;
assert_eq!(bseq!(-var:8), 0xff);Note: Since the macros are compiled into common bit manipulation operations, the usage of this macro doesn’t introduce additional runtime overhead.
The macro outputs a numerical value with the appropriate bits set, providing an efficient method to generate specific bit sequences.