Parse a flags value from text. This function will fail on any names that don't correspond to defined flags. Unknown bits will be retained. */
(input: &str)
| 97 | Unknown bits will be retained. |
| 98 | */ |
| 99 | pub fn from_str<B: Flags>(input: &str) -> Result<B, ParseError> |
| 100 | where |
| 101 | B::Bits: ParseHex, |
| 102 | { |
| 103 | let mut parsed_flags = B::empty(); |
| 104 | |
| 105 | // If the input is empty then return an empty set of flags |
| 106 | if input.trim().is_empty() { |
| 107 | return Ok(parsed_flags); |
| 108 | } |
| 109 | |
| 110 | for flag in input.split('|') { |
| 111 | let flag = flag.trim(); |
| 112 | |
| 113 | // If the flag is empty then we've got missing input |
| 114 | if flag.is_empty() { |
| 115 | return Err(ParseError::empty_flag()); |
| 116 | } |
| 117 | |
| 118 | // If the flag starts with `0x` then it's a hex number |
| 119 | // Parse it directly to the underlying bits type |
| 120 | let parsed_flag = if let Some(flag) = flag.strip_prefix("0x") { |
| 121 | let bits = |
| 122 | <B::Bits>::parse_hex(flag).map_err(|_| ParseError::invalid_hex_flag(flag))?; |
| 123 | |
| 124 | B::from_bits_retain(bits) |
| 125 | } |
| 126 | // Otherwise the flag is a name |
| 127 | // The generated flags type will determine whether |
| 128 | // or not it's a valid identifier |
| 129 | else { |
| 130 | B::from_name(flag).ok_or_else(|| ParseError::invalid_named_flag(flag))? |
| 131 | }; |
| 132 | |
| 133 | parsed_flags.insert(parsed_flag); |
| 134 | } |
| 135 | |
| 136 | Ok(parsed_flags) |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | Write a flags value as text, ignoring any unknown bits. |