1 | //! An example of implementing Rust's standard formatting and parsing traits for flags types. |
2 | |
3 | use core::{fmt, str}; |
4 | |
5 | bitflags::bitflags! { |
6 | // You can `#[derive]` the `Debug` trait, but implementing it manually |
7 | // can produce output like `A | B` instead of `Flags(A | B)`. |
8 | // #[derive(Debug)] |
9 | #[derive(PartialEq, Eq)] |
10 | pub struct Flags: u32 { |
11 | const A = 1; |
12 | const B = 2; |
13 | const C = 4; |
14 | const D = 8; |
15 | } |
16 | } |
17 | |
18 | impl fmt::Debug for Flags { |
19 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
20 | bitflags::parser::to_writer(self, f) |
21 | } |
22 | } |
23 | |
24 | impl fmt::Display for Flags { |
25 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
26 | bitflags::parser::to_writer(self, f) |
27 | } |
28 | } |
29 | |
30 | impl str::FromStr for Flags { |
31 | type Err = bitflags::parser::ParseError; |
32 | |
33 | fn from_str(flags: &str) -> Result<Self, Self::Err> { |
34 | bitflags::parser::from_str(flags) |
35 | } |
36 | } |
37 | |
38 | fn main() -> Result<(), bitflags::parser::ParseError> { |
39 | let flags = Flags::A | Flags::B; |
40 | |
41 | println!("{}" , flags); |
42 | |
43 | let formatted = flags.to_string(); |
44 | let parsed: Flags = formatted.parse()?; |
45 | |
46 | assert_eq!(flags, parsed); |
47 | |
48 | Ok(()) |
49 | } |
50 | |