Skip to content

Commit cde8802

Browse files
committed
int.__[r]floordiv__ to use BigInt.div_floor
1 parent cd8ee04 commit cde8802

2 files changed

Lines changed: 25 additions & 4 deletions

File tree

tests/snippets/ints.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,13 @@
3636
assert (2).__mul__(1) == 2
3737
assert (2).__rmul__(1) == 2
3838
assert (2).__truediv__(1) == 2.0
39+
with assertRaises(ZeroDivisionError):
40+
(2).__truediv__(0)
3941
assert (2).__rtruediv__(1) == 0.5
42+
assert (-2).__floordiv__(3) == -1
43+
with assertRaises(ZeroDivisionError):
44+
(2).__floordiv__(0)
45+
assert (-3).__rfloordiv__(2) == -1
4046
assert (-2).__divmod__(3) == (-1, 1)
4147
with assertRaises(ZeroDivisionError):
4248
(2).__divmod__(0)

vm/src/obj/objint.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -270,11 +270,26 @@ impl PyInt {
270270
fn floordiv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
271271
if objtype::isinstance(&other, &vm.ctx.int_type()) {
272272
let v2 = get_value(&other);
273-
if *v2 != BigInt::zero() {
274-
let modulo = (&self.value % v2 + v2) % v2;
275-
Ok(vm.ctx.new_int((&self.value - modulo) / v2))
273+
if v2.is_zero() {
274+
Err(vm.new_zero_division_error("integer division by zero".to_string()))
276275
} else {
277-
Err(vm.new_zero_division_error("integer floordiv by zero".to_string()))
276+
let v1 = &self.value;
277+
Ok(vm.ctx.new_int(v1.div_floor(v2)))
278+
}
279+
} else {
280+
Ok(vm.ctx.not_implemented())
281+
}
282+
}
283+
284+
#[pymethod(name = "__rfloordiv__")]
285+
fn rfloordiv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
286+
if objtype::isinstance(&other, &vm.ctx.int_type()) {
287+
let v2 = &self.value;
288+
if v2.is_zero() {
289+
Err(vm.new_zero_division_error("integer division by zero".to_string()))
290+
} else {
291+
let v1 = get_value(&other);
292+
Ok(vm.ctx.new_int(v1.div_floor(v2)))
278293
}
279294
} else {
280295
Ok(vm.ctx.not_implemented())

0 commit comments

Comments
 (0)