MCPcopy Index your code
hub / github.com/RustPython/RustPython / parse_str

Function parse_str

crates/literal/src/complex.rs:42–75  ·  view source on GitHub ↗

Parse a complex number from a string. Returns `Some((re, im))` on success.

(s: &str)

Source from the content-addressed store, hash-verified

40///
41/// Returns `Some((re, im))` on success.
42pub 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}

Callers

nothing calls this directly

Calls 5

trimMethod · 0.80
strip_prefixMethod · 0.80
strip_suffixMethod · 0.80
SomeClass · 0.50
as_bytesMethod · 0.45

Tested by

no test coverage detected