A set of defined flags using a bits type as storage. ## Implementing `Flags` This trait is implemented by the [`bitflags`](macro.bitflags.html) macro: ``` use bitflags::bitflags; bitflags! { struct MyFlags: u8 { const A = 1; const B = 1 << 1; } } ``` It can also be implemented manually: ``` use bitflags::{Flag, Flags}; struct MyFlags(u8); impl Flags for MyFlags {
| 130 | ``` |
| 131 | */ |
| 132 | pub trait Flags: Sized + 'static { |
| 133 | /// The set of defined flags. |
| 134 | const FLAGS: &'static [Flag<Self>]; |
| 135 | |
| 136 | /// The underlying bits type. |
| 137 | type Bits: Bits; |
| 138 | |
| 139 | /// Get a flags value with all bits unset. |
| 140 | fn empty() -> Self { |
| 141 | Self::from_bits_retain(Self::Bits::EMPTY) |
| 142 | } |
| 143 | |
| 144 | /// Get a flags value with all known bits set. |
| 145 | fn all() -> Self { |
| 146 | let mut truncated = Self::Bits::EMPTY; |
| 147 | |
| 148 | for flag in Self::FLAGS.iter() { |
| 149 | truncated = truncated | flag.value().bits(); |
| 150 | } |
| 151 | |
| 152 | Self::from_bits_retain(truncated) |
| 153 | } |
| 154 | |
| 155 | /// Get a flags value with all bits from named flags set. |
| 156 | /// |
| 157 | /// This method is equivalent to [`Flags::all`] unless [`Flags::FLAGS`] contains unnamed flags. |
| 158 | fn all_named() -> Self { |
| 159 | Self::from_bits_retain( |
| 160 | Self::FLAGS |
| 161 | .iter() |
| 162 | .filter(|f| !f.name().is_empty()) |
| 163 | .fold(Self::empty().bits(), |acc, f| acc | f.value().bits()), |
| 164 | ) |
| 165 | } |
| 166 | |
| 167 | /// Get the known bits from a flags value. |
| 168 | fn known_bits(&self) -> Self::Bits { |
| 169 | self.bits() & Self::all().bits() |
| 170 | } |
| 171 | |
| 172 | /// Get the unknown bits from a flags value. |
| 173 | fn unknown_bits(&self) -> Self::Bits { |
| 174 | self.bits() & !Self::all().bits() |
| 175 | } |
| 176 | |
| 177 | /// This method will return `true` if any unknown bits are set. |
| 178 | fn contains_unknown_bits(&self) -> bool { |
| 179 | self.unknown_bits() != Self::Bits::EMPTY |
| 180 | } |
| 181 | |
| 182 | /// Get the underlying bits value. |
| 183 | /// |
| 184 | /// The returned value is exactly the bits set in this flags value. |
| 185 | fn bits(&self) -> Self::Bits; |
| 186 | |
| 187 | /// Convert from a bits value. |
| 188 | /// |
| 189 | /// This method will return `None` if any unknown bits are set. |
no outgoing calls
no test coverage detected