Distinguish between to_index and to_index_opt · RustPython/RustPython@7beb932 · GitHub
Skip to content

Commit 7beb932

Browse files
committed
Distinguish between to_index and to_index_opt
1 parent 6ba5880 commit 7beb932

6 files changed

Lines changed: 25 additions & 45 deletions

File tree

vm/src/builtins/int.rs

Lines changed: 1 addition & 7 deletions

vm/src/builtins/slice.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ fn to_index_value(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Option<Big
274274
return Ok(None);
275275
}
276276

277-
let result = vm.to_index(obj).unwrap_or_else(|| {
277+
let result = vm.to_index_opt(obj.clone()).unwrap_or_else(|| {
278278
Err(vm.new_type_error(
279279
"slice indices must be integers or None or have an __index__ method".to_owned(),
280280
))

vm/src/bytesinner.rs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1189,15 +1189,7 @@ pub fn bytes_from_object(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Vec
11891189
}
11901190

11911191
pub fn value_from_object(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<u8> {
1192-
let value = vm.to_index(obj).ok_or_else(|| {
1193-
vm.new_type_error(format!(
1194-
"'{}' object cannot be interpreted as an integer",
1195-
obj.class().name
1196-
))
1197-
})?;
1198-
// __index__ returned non-int type
1199-
let value = value?;
1200-
value
1192+
vm.to_index(obj)?
12011193
.borrow_value()
12021194
.to_u8()
12031195
.ok_or_else(|| vm.new_value_error("byte must be in range(0, 256)".to_owned()))

vm/src/stdlib/math.rs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -131,15 +131,8 @@ fn math_sqrt(value: IntoPyFloat, vm: &VirtualMachine) -> PyResult<f64> {
131131
}
132132

133133
fn math_isqrt(x: PyObjectRef, vm: &VirtualMachine) -> PyResult<BigInt> {
134-
let index = vm.to_index(&x).ok_or_else(|| {
135-
vm.new_type_error(format!(
136-
"'{}' object cannot be interpreted as an integer",
137-
x.class().name
138-
))
139-
})?;
140-
// __index__ may have returned non-int type
141-
let python_value = index?;
142-
let value = python_value.borrow_value();
134+
let index = vm.to_index(&x)?;
135+
let value = index.borrow_value();
143136

144137
if value.is_negative() {
145138
return Err(vm.new_value_error("isqrt() argument must be nonnegative".to_owned()));

vm/src/stdlib/pystruct.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,7 @@ pub(crate) mod _struct {
444444
where
445445
T: num_traits::PrimInt + for<'a> std::convert::TryFrom<&'a BigInt>,
446446
{
447-
match vm.to_index(&arg) {
447+
match vm.to_index_opt(arg.clone()) {
448448
Some(index) => try_to_primitive(index?.borrow_value(), vm),
449449
None => Err(new_struct_error(
450450
vm,

vm/src/vm.rs

Lines changed: 19 additions & 18 deletions

0 commit comments

Comments
 (0)