Skip to content

Commit 8f5f91a

Browse files
authored
fix validation of ints with leading unary minus (#1291)
1 parent aed6844 commit 8f5f91a

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/input/shared.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,13 @@ fn clean_int_str(mut s: &str) -> Option<Cow<str>> {
114114
// strip leading and trailing whitespace
115115
s = s.trim();
116116

117-
// strip leading unary plus
118-
s = s.strip_prefix('+').unwrap_or(s);
117+
// Check for and remove a leading unary plus and ensure the next character is not a unary minus. e.g.: '+-1'.
118+
if let Some(suffix) = s.strip_prefix('+') {
119+
if suffix.starts_with('-') {
120+
return None;
121+
}
122+
s = suffix;
123+
}
119124

120125
// strip loading zeros
121126
s = strip_leading_zeros(s)?;
@@ -149,17 +154,17 @@ fn strip_leading_zeros(s: &str) -> Option<&str> {
149154
match char_iter.next() {
150155
// if we get a leading zero we continue
151156
Some((_, '0')) => (),
152-
// if we get another digit we return the whole string
153-
Some((_, c)) if ('1'..='9').contains(&c) => return Some(s),
157+
// if we get another digit or unary minus we return the whole string
158+
Some((_, c)) if ('1'..='9').contains(&c) || c == '-' => return Some(s),
154159
// anything else is invalid, we return None
155160
_ => return None,
156161
};
157162
for (i, c) in char_iter {
158163
match c {
159164
// continue on more leading zeros or if we get an underscore we continue - we're "within the number"
160165
'0' | '_' => (),
161-
// any other digit we return the rest of the string
162-
'1'..='9' => return Some(&s[i..]),
166+
// any other digit or unary minus we return the rest of the string
167+
'1'..='9' | '-' => return Some(&s[i..]),
163168
// if we get a dot we return the rest of the string but include the last zero
164169
'.' => return Some(&s[(i - 1)..]),
165170
// anything else is invalid, we return None

tests/validators/test_int.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
('+0_000', 0),
3030
(1, 1),
3131
(' 1 ', 1),
32+
('-1', -1),
33+
('-1.0', -1),
3234
(42, 42),
3335
('42', 42),
3436
(42.0, 42),
@@ -48,6 +50,7 @@
4850
('+4_2.0', 42),
4951
('+04_2.0', 42),
5052
('++4_2', Err('Input should be a valid integer, unable to parse string as an integer')),
53+
('-+1', Err('Input should be a valid integer, unable to parse string as an integer')),
5154
('+-1', Err('Input should be a valid integer, unable to parse string as an integer')),
5255
('4_2', 42),
5356
('0_42', 42),

0 commit comments

Comments
 (0)