Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trimming str before parsing to int and float #1203

Merged
merged 1 commit into from Feb 26, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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