1 //! An example of implementing the `BitFlags` trait manually for a flags type.
2 //!
3 //! This example doesn't use any macros.
4
5 use std::{fmt, str};
6
7 use bitflags::{Flag, Flags};
8
9 // First: Define your flags type. It just needs to be `Sized + 'static`.
10 pub struct ManualFlags(u32);
11
12 // Not required: Define some constants for valid flags
13 impl ManualFlags {
14 pub const A: ManualFlags = ManualFlags(0b00000001);
15 pub const B: ManualFlags = ManualFlags(0b00000010);
16 pub const C: ManualFlags = ManualFlags(0b00000100);
17 pub const ABC: ManualFlags = ManualFlags(0b00000111);
18 }
19
20 // Next: Implement the `BitFlags` trait, specifying your set of valid flags
21 // and iterators
22 impl Flags for ManualFlags {
23 const FLAGS: &'static [Flag<Self>] = &[
24 Flag::new("A", Self::A),
25 Flag::new("B", Self::B),
26 Flag::new("C", Self::C),
27 ];
28
29 type Bits = u32;
30
bits(&self) -> u3231 fn bits(&self) -> u32 {
32 self.0
33 }
34
from_bits_retain(bits: u32) -> Self35 fn from_bits_retain(bits: u32) -> Self {
36 Self(bits)
37 }
38 }
39
40 // Not required: Add parsing support
41 impl str::FromStr for ManualFlags {
42 type Err = bitflags::parser::ParseError;
43
from_str(input: &str) -> Result<Self, Self::Err>44 fn from_str(input: &str) -> Result<Self, Self::Err> {
45 bitflags::parser::from_str(input)
46 }
47 }
48
49 // Not required: Add formatting support
50 impl fmt::Display for ManualFlags {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 bitflags::parser::to_writer(self, f)
53 }
54 }
55
main()56 fn main() {
57 println!(
58 "{}",
59 ManualFlags::A.union(ManualFlags::B).union(ManualFlags::C)
60 );
61 }
62