Skip to content

Commit 7fd01b0

Browse files
Merge pull request RustPython#1231 from yjhmelody/fix_int_fn
fix int fn
2 parents 96bd5a6 + c758b36 commit 7fd01b0

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

tests/snippets/ints.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,10 @@
9090
assert int("101", 2) == 5
9191
assert int("101", base=2) == 5
9292
assert int(1) == 1
93+
assert int(' 1') == 1
94+
assert int('1 ') == 1
95+
assert int(' 1 ') == 1
96+
assert int('10', base=0) == 10
9397

9498
assert int.from_bytes(b'\x00\x10', 'big') == 16
9599
assert int.from_bytes(b'\x00\x10', 'little') == 4096
@@ -103,6 +107,13 @@
103107
assert (2147483647).to_bytes(8, 'big', signed=False) == b'\x00\x00\x00\x00\x7f\xff\xff\xff'
104108
assert (-2147483648).to_bytes(8, 'little', signed=True) == b'\x00\x00\x00\x80\xff\xff\xff\xff'
105109

110+
with assertRaises(ValueError):
111+
# check base first
112+
int(' 1 ', base=1)
113+
114+
with assertRaises(ValueError):
115+
int(' 1 ', base=37)
116+
106117
with assertRaises(TypeError):
107118
int(base=2)
108119

vm/src/obj/objint.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use num_traits::{One, Pow, Signed, ToPrimitive, Zero};
66

77
use crate::format::FormatSpec;
88
use crate::function::{KwArgs, OptionalArg, PyFuncArgs};
9+
use crate::obj::objtype::PyClassRef;
910
use crate::pyhash;
1011
use crate::pyobject::{
1112
IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
@@ -17,7 +18,6 @@ use super::objbyteinner::PyByteInner;
1718
use super::objbytes::PyBytes;
1819
use super::objstr::{PyString, PyStringRef};
1920
use super::objtype;
20-
use crate::obj::objtype::PyClassRef;
2121

2222
/// int(x=0) -> integer
2323
/// int(x, base=10) -> integer
@@ -667,10 +667,16 @@ fn int_new(cls: PyClassRef, options: IntOptions, vm: &VirtualMachine) -> PyResul
667667
}
668668

669669
// Casting function:
670-
pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, base: u32) -> PyResult<BigInt> {
670+
pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, mut base: u32) -> PyResult<BigInt> {
671+
if base == 0 {
672+
base = 10
673+
} else if base < 2 || base > 36 {
674+
return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_string()));
675+
}
676+
671677
match_class!(obj.clone(),
672678
s @ PyString => {
673-
i32::from_str_radix(s.as_str(), base)
679+
i32::from_str_radix(s.as_str().trim(), base)
674680
.map(BigInt::from)
675681
.map_err(|_|vm.new_value_error(format!(
676682
"invalid literal for int() with base {}: '{}'",

0 commit comments

Comments
 (0)