Skip to content

Commit 09710b5

Browse files
committed
Add float.__rdivmod__ and div/mod tests
1 parent 813307f commit 09710b5

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

tests/snippets/floats.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@
106106
assert 2.0.__rmul__(1.0) == 2.0
107107
assert 1.0.__truediv__(2.0) == 0.5
108108
assert 1.0.__rtruediv__(2.0) == 2.0
109+
assert 2.5.__divmod__(2.0) == (1.0, 0.5)
110+
assert 2.0.__rdivmod__(2.5) == (1.0, 0.5)
109111

110112
assert 1.0.__add__(1) == 2.0
111113
assert 1.0.__radd__(1) == 2.0
@@ -120,6 +122,11 @@
120122
assert_raises(ZeroDivisionError, lambda: 2.0 / 0)
121123
assert_raises(ZeroDivisionError, lambda: 2.0 // 0)
122124
assert_raises(ZeroDivisionError, lambda: 2.0 % 0)
125+
assert_raises(ZeroDivisionError, lambda: divmod(2.0, 0))
126+
assert_raises(ZeroDivisionError, lambda: 2 / 0.0)
127+
assert_raises(ZeroDivisionError, lambda: 2 // 0.0)
128+
assert_raises(ZeroDivisionError, lambda: 2 % 0.0)
129+
# assert_raises(ZeroDivisionError, lambda: divmod(2, 0.0))
123130

124131
assert 1.2.__int__() == 1
125132
assert 1.2.__float__() == 1.2

vm/src/obj/objfloat.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,14 @@ fn inner_floordiv(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> {
7575
}
7676
}
7777

78+
fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> {
79+
if v2 != 0.0 {
80+
Ok(((v1 / v2).floor(), v1 % v2))
81+
} else {
82+
Err(vm.new_zero_division_error("float divmod()".to_string()))
83+
}
84+
}
85+
7886
#[pyimpl]
7987
impl PyFloat {
8088
#[pymethod(name = "__eq__")]
@@ -177,8 +185,20 @@ impl PyFloat {
177185
try_float(&other, vm)?.map_or_else(
178186
|| Ok(vm.ctx.not_implemented()),
179187
|other| {
180-
let r1 = inner_floordiv(self.value, other, vm)?;
181-
let r2 = inner_mod(self.value, other, vm)?;
188+
let (r1, r2) = inner_divmod(self.value, other, vm)?;
189+
Ok(vm
190+
.ctx
191+
.new_tuple(vec![vm.ctx.new_float(r1), vm.ctx.new_float(r2)]))
192+
},
193+
)
194+
}
195+
196+
#[pymethod(name = "__rdivmod__")]
197+
fn rdivmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
198+
try_float(&other, vm)?.map_or_else(
199+
|| Ok(vm.ctx.not_implemented()),
200+
|other| {
201+
let (r1, r2) = inner_divmod(other, self.value, vm)?;
182202
Ok(vm
183203
.ctx
184204
.new_tuple(vec![vm.ctx.new_float(r1), vm.ctx.new_float(r2)]))

0 commit comments

Comments
 (0)