| 183 | } |
| 184 | |
| 185 | pub fn from_hex(s: &str) -> Option<f64> { |
| 186 | if let Ok(f) = hexf_parse::parse_hexf64(s, false) { |
| 187 | return Some(f); |
| 188 | } |
| 189 | match s.to_ascii_lowercase().as_str() { |
| 190 | "nan" | "+nan" | "-nan" => Some(f64::NAN), |
| 191 | "inf" | "infinity" | "+inf" | "+infinity" => Some(f64::INFINITY), |
| 192 | "-inf" | "-infinity" => Some(f64::NEG_INFINITY), |
| 193 | value => { |
| 194 | let mut hex = String::with_capacity(value.len()); |
| 195 | let has_0x = value.contains("0x"); |
| 196 | let has_p = value.contains('p'); |
| 197 | let has_dot = value.contains('.'); |
| 198 | let mut start = 0; |
| 199 | |
| 200 | if !has_0x && value.starts_with('-') { |
| 201 | hex.push_str("-0x"); |
| 202 | start += 1; |
| 203 | } else if !has_0x { |
| 204 | hex.push_str("0x"); |
| 205 | if value.starts_with('+') { |
| 206 | start += 1; |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | for (index, ch) in value.chars().enumerate() { |
| 211 | if ch == 'p' { |
| 212 | if has_dot { |
| 213 | hex.push('p'); |
| 214 | } else { |
| 215 | hex.push_str(".p"); |
| 216 | } |
| 217 | } else if index >= start { |
| 218 | hex.push(ch); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | if !has_p && has_dot { |
| 223 | hex.push_str("p0"); |
| 224 | } else if !has_p && !has_dot { |
| 225 | hex.push_str(".p0") |
| 226 | } |
| 227 | |
| 228 | hexf_parse::parse_hexf64(hex.as_str(), false).ok() |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | pub fn to_hex(value: f64) -> String { |
| 234 | let (mantissa, exponent, sign) = value.integer_decode(); |