Expand description
Parsing flags from text.
§Grammar
Format and parse a flags value as text using the following grammar:
- Flags: (Whitespace Flag Whitespace)
|
* - Flag: Name | Hex Number
- Name: The name of any defined flag
- Hex Number:
0x
([0-9a-fA-F])* - Whitespace: (\s)*
Flags values can be formatted as Flags by iterating over them, formatting each yielded flags value as a Flag. Any yielded flags value that sets exactly the bits of a defined flag with a name should be formatted as a Name. Otherwise it must be formatted as a Hex Number.
Text that is empty or whitespace is an empty flags value.
§Modes
Formatting and parsing supports three modes:
- Retain: Formatting and parsing roundtrips exactly the bits of the source flags value. This is the default behavior.
- Truncate: Flags values are truncated before formatting, and truncated after parsing.
- Strict: A Flag may only be formatted and parsed as a Name. Hex numbers are not allowed. A consequence of this is that unknown bits and any bits that aren’t in a contained named flag will be ignored. This is recommended for flags values serialized across API boundaries, like web services.
Given the following flags type:
#[bitflag(u8)]
#[derive(Clone, Copy)]
enum Flags {
A = 0b0000_0001,
B = 0b0000_0010,
AB = 0b0000_0011,
C = 0b0000_1100,
}
The following are examples of how flags values can be formatted using any mode:
0b0000_0000 = ""
0b0000_0001 = "A"
0b0000_0010 = "B"
0b0000_0011 = "A | B"
0b0000_0011 = "AB"
0b0000_1111 = "A | B | C"
Truncate mode will unset any unknown bits:
0b1000_0000 = ""
0b1111_1111 = "A | B | C"
0b0000_1000 = "0x8"
Retain mode will include any unknown bits as a final Flag:
0b1000_0000 = "0x80"
0b1111_1111 = "A | B | C | 0xf0"
0b0000_1000 = "0x8"
Strict mode will unset any unknown bits, as well as bits not contained in any defined named flags:
0b1000_0000 = ""
0b1111_1111 = "A | B | C"
0b0000_1000 = ""
§Example
As an example, this is how Flags::A | Flags::B | 0x0c
can be represented as text:
A | B | 0x0c
Alternatively, it could be represented without whitespace:
A|B|0x0C
Note that identifiers are case-sensitive, so the following is not equivalent:
a|b|0x0C
Structs§
- Parse
Error - An error encountered while parsing flags from text.
Traits§
- Parse
Hex - Parse a value from a hex string.
Functions§
- from_
text - Parse a flags value from text.
- from_
text_ strict - Parse a flags value from text.
- from_
text_ truncate - Parse a flags value from text.
- to_
writer - Write a flags value as text.
- to_
writer_ strict - Write only the contained, defined, named flags in a flags value as text.
- to_
writer_ truncate - Write a flags value as text, ignoring any unknown bits.