Skip to content

Commit

Permalink
Trimming str before parsing to int and float (#1203)
Browse files Browse the repository at this point in the history
Co-authored-by: Hung Tse Lee <hungtsetse@tse-mac.local>
  • Loading branch information
hungtsetse and Hung Tse Lee committed Feb 26, 2024
1 parent 47aff70 commit 1a90468
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/input/shared.rs
Expand Up @@ -72,6 +72,7 @@ fn strip_underscores(s: &str) -> Option<String> {
/// https://docs.python.org/3/whatsnew/3.11.html#other-cpython-implementation-changes and
/// https://github.com/python/cpython/issues/95778 for more info in that length bound
pub fn str_as_int<'s, 'l>(input: &'s impl Input<'s>, str: &'l str) -> ValResult<EitherInt<'s>> {
let str = str.trim();
let len = str.len();
if len > 4300 {
Err(ValError::new(ErrorTypeDefaults::IntParsingSize, input))
Expand All @@ -96,7 +97,7 @@ pub fn str_as_int<'s, 'l>(input: &'s impl Input<'s>, str: &'l str) -> ValResult<

/// parse a float as a float
pub fn str_as_float<'s, 'l>(input: &'s impl Input<'s>, str: &'l str) -> ValResult<EitherFloat<'s>> {
match str.parse() {
match str.trim().parse() {
Ok(float) => Ok(EitherFloat::F64(float)),
Err(_) => match strip_underscores(str).and_then(|stripped| stripped.parse().ok()) {
Some(float) => Ok(EitherFloat::F64(float)),
Expand Down
1 change: 1 addition & 0 deletions tests/validators/test_float.py
Expand Up @@ -20,6 +20,7 @@
(1, 1),
(42, 42),
('42', 42),
(' 42.1 ', 42.1),
('42.123', 42.123),
(42.0, 42),
(42.5, 42.5),
Expand Down
1 change: 1 addition & 0 deletions tests/validators/test_int.py
Expand Up @@ -21,6 +21,7 @@
(0, 0),
('0', 0),
(1, 1),
(' 1 ', 1),
(42, 42),
('42', 42),
(42.0, 42),
Expand Down

0 comments on commit 1a90468

Please sign in to comment.