Debian Codegraph @

examples/bits_position.rs

raw
1 use bitfield::bitfield;
2 use bitfield::BitMut;
3 use bitfield::BitRangeMut;
4
5 bitfield! {
6 struct BitsLocations([u8]);
7 }
8
9 bitfield! {
10 struct BitsLocationsMsb0(MSB0 [u8]);
11 }
12
13 fn println_slice_bits(slice: &[u8]) {
14 if slice.is_empty() {
15 println!("[]");
16 } else {
17 print!("[{:08b}", slice[0]);
18
19 for byte in &slice[1..] {
20 print!(", {:08b}", byte);
21 }
22
23 println!("]");
24 }
25 }
26
27 fn main() {
28 let mut bits_locations = BitsLocations([0; 3]);
29 let mut bits_locations_msb0 = BitsLocationsMsb0([0; 3]);
30
31 println!("Default version:");
32 for i in 0..(3 * 8) {
33 bits_locations.set_bit(i, true);
34 print!("{:2}: ", i);
35 println_slice_bits(&bits_locations.0);
36 bits_locations.set_bit(i, false);
37 }
38
39 for i in 0..(3 * 8 - 3) {
40 let msb = i + 3;
41 let lsb = i;
42 for value in &[0b1111u8, 0b0001, 0b1000] {
43 bits_locations.set_bit_range(msb, lsb, *value);
44 print!("{:2} - {:2} ({:04b}): ", msb, lsb, value);
45 println_slice_bits(&bits_locations.0);
46 }
47 println!();
48 bits_locations.set_bit_range(msb, lsb, 0u8);
49 }
50
51 println!("MSB0 version:");
52
53 for i in 0..(3 * 8) {
54 bits_locations_msb0.set_bit(i, true);
55 print!("{:2}: ", i);
56 println_slice_bits(&bits_locations_msb0.0);
57
58 bits_locations_msb0.set_bit(i, false);
59 }
60
61 for i in 0..(3 * 8 - 3) {
62 let msb = i + 3;
63 let lsb = i;
64 for value in &[0b1111u8, 0b0001, 0b1000] {
65 bits_locations_msb0.set_bit_range(msb, lsb, *value);
66 print!("{:2} - {:2} ({:04b}): ", msb, lsb, value);
67 println_slice_bits(&bits_locations_msb0.0);
68 }
69 println!();
70
71 bits_locations_msb0.set_bit_range(msb, lsb, 0u8);
72 }
73 }