Skip to content

Commit

Permalink
Negative integers with leading zeros raise ValueError (#1436)
Browse files Browse the repository at this point in the history
  • Loading branch information
JBLDKY authored Sep 5, 2024
1 parent e1cd613 commit dec5faa
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/input/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,22 @@ fn clean_int_str(mut s: &str) -> Option<Cow<str>> {
s = suffix;
}

// Remember if the number is negative
// the `strip_leading_zeros` function will not strip leading zeros for negative numbers
// therefore we simply "take away" the unary minus sign temporarily and add it back before
// returning. This allows consistent handling of leading zeros for both positive and negative numbers.
let mut is_negative = false;
if let Some(suffix) = s.strip_prefix('-') {
// Invalidate "--" and "-+" as an integer prefix by returning None
if suffix.starts_with('-') | suffix.starts_with('+') {
return None;
}

is_negative = true;
// Continue as usual without the unary minus sign
s = suffix;
}

// strip loading zeros
s = strip_leading_zeros(s)?;

Expand All @@ -136,13 +152,20 @@ fn clean_int_str(mut s: &str) -> Option<Cow<str>> {

// remove underscores
if let Some(str_stripped) = strip_underscores(s) {
Some(str_stripped.into())
} else {
match len_before == s.len() {
true => None,
false => Some(s.into()),
match is_negative {
true => return Some(("-".to_string() + &str_stripped).into()),
false => return Some(str_stripped.into()),
}
}

if len_before == s.len() {
return None;
}

match is_negative {
true => Some(("-".to_string() + s).into()),
false => Some(s.into()),
}
}

/// strip leading zeros from a string, we can't simple use `s.trim_start_matches('0')`, because:
Expand Down
6 changes: 6 additions & 0 deletions tests/validators/test_int.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@
('++4_2', Err('Input should be a valid integer, unable to parse string as an integer')),
('-+1', Err('Input should be a valid integer, unable to parse string as an integer')),
('+-1', Err('Input should be a valid integer, unable to parse string as an integer')),
('--0001', Err('Input should be a valid integer, unable to parse string as an integer')),
('-+0001', Err('Input should be a valid integer, unable to parse string as an integer')),
('-0-001', Err('Input should be a valid integer, unable to parse string as an integer')),
('-0+001', Err('Input should be a valid integer, unable to parse string as an integer')),
('-00001', -1),
('-00042_000', -42000),
('4_2', 42),
('0_42', 42),
('4_2.0', 42),
Expand Down

0 comments on commit dec5faa

Please sign in to comment.