Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions crates/literal/src/complex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ pub fn parse_str(s: &str) -> Option<(f64, f64)> {
Some(s) => s.strip_suffix(')')?.trim(),
};

// Whitespace is only allowed around the whole string and the optional
// parentheses, never inside the numeric token. Reject it here so that
// `float::parse_str` (which tolerates surrounding whitespace on a part)
// does not let e.g. "1 +2j" through.
if s.contains(char::is_whitespace) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a test in extra_tests

return None;
}

let value = match s.strip_suffix(|c| c == 'j' || c == 'J') {
None => (float::parse_str(s)?, 0.0),
Some(mut s) => {
Expand All @@ -96,3 +104,39 @@ pub fn parse_str(s: &str) -> Option<(f64, f64)> {
};
Some(value)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn parse_rejects_internal_whitespace() {
// Whitespace inside the numeric token is invalid, even where a bare
// `float::parse_str` on a fragment would tolerate it.
for s in [
"1 +2j", "1 2j", "1 +2 j", "+ 1j", "1.5 j", "(1 +2j)", "2 -3j",
] {
assert_eq!(parse_str(s), None, "{s:?} must not parse");
}
}

#[test]
fn parse_allows_surrounding_and_paren_whitespace() {
for s in [" 1+2j ", " (1+2j) ", "( 1+2j )"] {
assert_eq!(parse_str(s), Some((1.0, 2.0)), "{s:?}");
}
}

#[test]
fn parse_basic() {
assert_eq!(parse_str("1"), Some((1.0, 0.0)));
assert_eq!(parse_str("1j"), Some((0.0, 1.0)));
assert_eq!(parse_str("j"), Some((0.0, 1.0)));
assert_eq!(parse_str("-j"), Some((0.0, -1.0)));
assert_eq!(parse_str("1+2j"), Some((1.0, 2.0)));
assert_eq!(parse_str("1e5j"), Some((0.0, 1e5)));
assert_eq!(parse_str("1_000"), Some((1000.0, 0.0)));
assert_eq!(parse_str(""), None);
assert_eq!(parse_str("abc"), None);
}
}
9 changes: 9 additions & 0 deletions extra_tests/snippets/builtin_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,15 @@ def __eq__(self, other):
assert_raises(TypeError, lambda: complex("5+2j", 1))
assert_raises(ValueError, lambda: complex("abc"))

# whitespace is allowed around the string and the optional parentheses,
# but not inside the numeric token
assert complex(" 1+2j ") == 1 + 2j
assert complex("(1+2j)") == 1 + 2j
assert complex(" ( 1+2j ) ") == 1 + 2j
assert_raises(ValueError, lambda: complex("1 +2j"))
assert_raises(ValueError, lambda: complex("1+ 2j"))
assert_raises(ValueError, lambda: complex("1 + 2j"))

assert complex("1+10j") == 1 + 10j
assert complex(10) == 10 + 0j
assert complex(10.0) == 10 + 0j
Expand Down
Loading