How to do it...

  1. Open the Cargo.toml file that was generated earlier for you.

  2. Under [dependencies], add the following lines:
bitflags = "1.0"
  1. If you want, you can go to bitflags' crates.io page (https://crates.io/crates/bitflags) to check for the newest version and use that one instead.
  2. In the bin folder, create a file called bit_fields.rs.

  3. Add the following code and run it with cargo run --bin bit_fields:

1    #[macro_use]
2 extern crate bitflags;
3
4 bitflags! {
5 struct Spices: u32 {
6 const SALT = 0b0000_0001;
7 const PEPPER = 0b0000_0010;
8 const CHILI = 0b0000_0100;
9 const SAFFRON = 0b0000_1000;
10 const ALL = Self::SALT.bits
11 | Self::PEPPER.bits
12 | Self::CHILI.bits
13 | Self::SAFFRON.bits;
14 }
15 }
16
17 impl Spices {
18 // Implementing a "clear" method can be useful
19 pub fn clear(&mut self) -> &mut Self {
20 self.bits = 0;
21 self
22 }
23 }
24
25 fn main() {
26 let classic = Spices::SALT | Spices::PEPPER;
27 let spicy = Spices::PEPPER | Spices::CHILI;
28 // Bit fields can nicely be printed
29 println!("Classic: {:?}", classic);
30 println!("Bits: {:08b}", classic.bits());
31 println!("Spicy: {:?}", spicy);
32 println!("Bits: {:08b}", spicy.bits());
33
34 println!();
35
36 // Use set operations
37 println!("Union: {:?}", classic | spicy);
38 println!("Intersection: {:?}", classic & spicy);
39 println!("Difference: {:?}", classic - spicy);
40 println!("Complement: {:?}", !classic);
41
42 // Interact with flags in a bit field
43 let mut custom = classic | spicy;
44 println!("Custom spice mix: {:?}", custom);
45 custom.insert(Spices::SAFFRON);
46 // Note that ALL is now also contained in the bit field
47 println!("Custom spice after adding saffron: {:?}", custom);
48 custom.toggle(Spices::CHILI);
49 println!("Custom spice after toggling chili: {:?}", custom);
50 custom.remove(Spices::SALT);
51 println!("Custom spice after removing salt: {:?}", custom);
52
53 // This could be user input
54 let wants_salt = true;
55 custom.set(Spices::SALT, wants_salt);
56 if custom.contains(Spices::SALT) {
57 println!("I hope I didn't put too much salt in it");
58 }
59
60 // Read flags from raw bits
61 let bits = 0b0000_1101;
62 if let Some(from_bits) = Spices::from_bits(bits) {
63 println!("The bits {:08b} represent the flags {:?}", bits,
from_bits);
64 }
65
66 custom.clear();
67 println!("Custom spice mix after clearing: {:?}", custom);
68 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.59