macro_bits/
bit.rs

1#[macro_export]
2/// Generate a mask from one or more bit indices.
3///
4/// ```
5/// use macro_bits::bit;
6///
7/// const SINGLE_BIT: u8 = bit!(0);
8/// const MULTIPLE_BITS: u8 = bit!(1,2);
9///
10/// assert_eq!(SINGLE_BIT, 1);
11/// assert_eq!(MULTIPLE_BITS, 6);
12/// ```
13macro_rules! bit {
14    ($index:expr) => {
15        (1 << $index)
16    };
17    ($($index:expr), +) => {
18        $(bit!($index) | )+ 0
19    };
20}
21#[macro_export]
22/// Check if a bit is set.
23///
24/// ```
25/// use macro_bits::{check_bit, bit};
26///
27/// const MASK: u8 = bit!(1,2);
28///
29/// assert!(check_bit!(0xff, MASK));
30/// ```
31macro_rules! check_bit {
32    ($flags:expr, $mask:expr) => {
33        ($flags & $mask != 0x0)
34    };
35}
36#[macro_export]
37/// Set a bit.
38///
39/// ```
40/// use macro_bits::{set_bit, bit};
41///
42/// const MASK1: u8 = bit!(0,1);
43/// const MASK2: u8 = bit!(2,3);
44///
45/// let mut data = 0;
46///
47/// set_bit!(data, MASK1);
48///
49/// let condition = true;
50/// set_bit!(data, MASK2, condition);
51///
52/// assert!(data == MASK1 | MASK2);
53/// ```
54macro_rules! set_bit {
55    ($flags:expr, $mask:expr) => {
56        $flags |= $mask
57    };
58    ($flags:expr, $mask:expr, $value:expr) => {
59        if $value {
60            set_bit!($flags, $mask);
61        }
62    };
63}