1use std::ops::{BitAnd, BitOr, BitXor, Not};
2
3use bitflags::{Bits, Flag, Flags};
4
5// Define a custom container that can be used in flags types
6// Note custom bits types can't be used in `bitflags!`
7// without making the trait impls `const`. This is currently
8// unstable
9#[derive(Clone, Copy, Debug)]
10pub struct CustomBits([bool; 3]);
11
12impl Bits for CustomBits {
13 const EMPTY: Self = CustomBits([false; 3]);
14
15 const ALL: Self = CustomBits([true; 3]);
16}
17
18impl PartialEq for CustomBits {
19 fn eq(&self, other: &Self) -> bool {
20 self.0 == other.0
21 }
22}
23
24impl BitAnd for CustomBits {
25 type Output = Self;
26
27 fn bitand(self, other: Self) -> Self {
28 CustomBits([
29 self.0[0] & other.0[0],
30 self.0[1] & other.0[1],
31 self.0[2] & other.0[2],
32 ])
33 }
34}
35
36impl BitOr for CustomBits {
37 type Output = Self;
38
39 fn bitor(self, other: Self) -> Self {
40 CustomBits([
41 self.0[0] | other.0[0],
42 self.0[1] | other.0[1],
43 self.0[2] | other.0[2],
44 ])
45 }
46}
47
48impl BitXor for CustomBits {
49 type Output = Self;
50
51 fn bitxor(self, other: Self) -> Self {
52 CustomBits([
53 self.0[0] & other.0[0],
54 self.0[1] & other.0[1],
55 self.0[2] & other.0[2],
56 ])
57 }
58}
59
60impl Not for CustomBits {
61 type Output = Self;
62
63 fn not(self) -> Self {
64 CustomBits([!self.0[0], !self.0[1], !self.0[2]])
65 }
66}
67
68#[derive(Clone, Copy, Debug)]
69pub struct CustomFlags(CustomBits);
70
71impl CustomFlags {
72 pub const A: Self = CustomFlags(CustomBits([true, false, false]));
73 pub const B: Self = CustomFlags(CustomBits([false, true, false]));
74 pub const C: Self = CustomFlags(CustomBits([false, false, true]));
75}
76
77impl Flags for CustomFlags {
78 const FLAGS: &'static [Flag<Self>] = &[
79 Flag::new("A", Self::A),
80 Flag::new("B", Self::B),
81 Flag::new("C", Self::C),
82 ];
83
84 type Bits = CustomBits;
85
86 fn bits(&self) -> Self::Bits {
87 self.0
88 }
89
90 fn from_bits_retain(bits: Self::Bits) -> Self {
91 CustomFlags(bits)
92 }
93}
94
95fn main() {
96 println!("{:?}", CustomFlags::A.union(CustomFlags::C));
97}
98