Parse a hexadecimal string to `ConstantData`. This is the inverse of `Display::fmt`. ``` use cranelift_codegen::ir::ConstantData; let c: ConstantData = "0x000102".parse().unwrap(); assert_eq!(c.into_vec(), [2, 1, 0]); ```
(s: &str)
| 146 | /// assert_eq!(c.into_vec(), [2, 1, 0]); |
| 147 | /// ``` |
| 148 | fn from_str(s: &str) -> Result<Self, &'static str> { |
| 149 | if s.len() <= 2 || &s[0..2] != "0x" { |
| 150 | return Err("Expected a hexadecimal string, e.g. 0x1234"); |
| 151 | } |
| 152 | |
| 153 | // clean and check the string |
| 154 | let cleaned: Vec<u8> = s[2..] |
| 155 | .as_bytes() |
| 156 | .iter() |
| 157 | .filter(|&&b| b as char != '_') |
| 158 | .cloned() |
| 159 | .collect(); // remove 0x prefix and any intervening _ characters |
| 160 | |
| 161 | if cleaned.is_empty() { |
| 162 | Err("Hexadecimal string must have some digits") |
| 163 | } else if cleaned.len() % 2 != 0 { |
| 164 | Err("Hexadecimal string must have an even number of digits") |
| 165 | } else if cleaned.len() > 32 { |
| 166 | Err("Hexadecimal string has too many digits to fit in a 128-bit vector") |
| 167 | } else { |
| 168 | let mut buffer = Vec::with_capacity((s.len() - 2) / 2); |
| 169 | for i in (0..cleaned.len()).step_by(2) { |
| 170 | let pair = from_utf8(&cleaned[i..i + 2]) |
| 171 | .or_else(|_| Err("Unable to parse hexadecimal pair as UTF-8"))?; |
| 172 | let byte = u8::from_str_radix(pair, 16) |
| 173 | .or_else(|_| Err("Unable to parse as hexadecimal"))?; |
| 174 | buffer.insert(0, byte); |
| 175 | } |
| 176 | Ok(Self(buffer)) |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | /// Maintains the mapping between a constant handle (i.e. [`Constant`]) and |