Parse a complex number from a string. Returns `Some((re, im))` on success.
(s: &str)
| 40 | /// |
| 41 | /// Returns `Some((re, im))` on success. |
| 42 | pub fn parse_str(s: &str) -> Option<(f64, f64)> { |
| 43 | let s = s.trim(); |
| 44 | // Handle parentheses |
| 45 | let s = match s.strip_prefix('(') { |
| 46 | None => s, |
| 47 | Some(s) => s.strip_suffix(')')?.trim(), |
| 48 | }; |
| 49 | |
| 50 | let value = match s.strip_suffix(|c| c == 'j' || c == 'J') { |
| 51 | None => (float::parse_str(s)?, 0.0), |
| 52 | Some(mut s) => { |
| 53 | let mut real = 0.0; |
| 54 | // Find the central +/- operator. If it exists, parse the real part. |
| 55 | for (i, w) in s.as_bytes().windows(2).enumerate() { |
| 56 | if (w[1] == b'+' || w[1] == b'-') && !(w[0] == b'e' || w[0] == b'E') { |
| 57 | real = float::parse_str(&s[..=i])?; |
| 58 | s = &s[i + 1..]; |
| 59 | break; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | let imag = match s { |
| 64 | // "j", "+j" |
| 65 | "" | "+" => 1.0, |
| 66 | // "-j" |
| 67 | "-" => -1.0, |
| 68 | s => float::parse_str(s)?, |
| 69 | }; |
| 70 | |
| 71 | (real, imag) |
| 72 | } |
| 73 | }; |
| 74 | Some(value) |
| 75 | } |
nothing calls this directly
no test coverage detected