Skip to content

Commit dec5faa

Browse files
authored
Negative integers with leading zeros raise ValueError (#1436)
1 parent e1cd613 commit dec5faa

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

src/input/shared.rs

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,22 @@ fn clean_int_str(mut s: &str) -> Option<Cow<str>> {
122122
s = suffix;
123123
}
124124

125+
// Remember if the number is negative
126+
// the `strip_leading_zeros` function will not strip leading zeros for negative numbers
127+
// therefore we simply "take away" the unary minus sign temporarily and add it back before
128+
// returning. This allows consistent handling of leading zeros for both positive and negative numbers.
129+
let mut is_negative = false;
130+
if let Some(suffix) = s.strip_prefix('-') {
131+
// Invalidate "--" and "-+" as an integer prefix by returning None
132+
if suffix.starts_with('-') | suffix.starts_with('+') {
133+
return None;
134+
}
135+
136+
is_negative = true;
137+
// Continue as usual without the unary minus sign
138+
s = suffix;
139+
}
140+
125141
// strip loading zeros
126142
s = strip_leading_zeros(s)?;
127143

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

137153
// remove underscores
138154
if let Some(str_stripped) = strip_underscores(s) {
139-
Some(str_stripped.into())
140-
} else {
141-
match len_before == s.len() {
142-
true => None,
143-
false => Some(s.into()),
155+
match is_negative {
156+
true => return Some(("-".to_string() + &str_stripped).into()),
157+
false => return Some(str_stripped.into()),
144158
}
145159
}
160+
161+
if len_before == s.len() {
162+
return None;
163+
}
164+
165+
match is_negative {
166+
true => Some(("-".to_string() + s).into()),
167+
false => Some(s.into()),
168+
}
146169
}
147170

148171
/// strip leading zeros from a string, we can't simple use `s.trim_start_matches('0')`, because:

tests/validators/test_int.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@
5252
('++4_2', Err('Input should be a valid integer, unable to parse string as an integer')),
5353
('-+1', Err('Input should be a valid integer, unable to parse string as an integer')),
5454
('+-1', Err('Input should be a valid integer, unable to parse string as an integer')),
55+
('--0001', Err('Input should be a valid integer, unable to parse string as an integer')),
56+
('-+0001', Err('Input should be a valid integer, unable to parse string as an integer')),
57+
('-0-001', Err('Input should be a valid integer, unable to parse string as an integer')),
58+
('-0+001', Err('Input should be a valid integer, unable to parse string as an integer')),
59+
('-00001', -1),
60+
('-00042_000', -42000),
5561
('4_2', 42),
5662
('0_42', 42),
5763
('4_2.0', 42),

0 commit comments

Comments
 (0)