Skip to content

Commit fbd0c59

Browse files
authored
Merge pull request RustPython#1074 from JimJeon/feature/rmod
Implement int.__rmod__
2 parents 5b534ad + 2f1d4a8 commit fbd0c59

2 files changed

Lines changed: 30 additions & 6 deletions

File tree

tests/snippets/ints.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@
4040
assert (2).__pow__(3) == 8
4141
assert (10).__pow__(-1) == 0.1
4242
assert (2).__rpow__(3) == 9
43+
assert (10).__mod__(5) == 0
44+
assert (10).__mod__(6) == 4
45+
with assertRaises(ZeroDivisionError):
46+
(10).__mod__(0)
47+
assert (5).__rmod__(10) == 0
48+
assert (6).__rmod__(10) == 4
49+
with assertRaises(ZeroDivisionError):
50+
(0).__rmod__(10)
4351

4452
# real/imag attributes
4553
assert (1).real == 1
@@ -63,6 +71,8 @@
6371
assert (2).__rtruediv__(1.0) == NotImplemented
6472
assert (2).__pow__(3.0) == NotImplemented
6573
assert (2).__rpow__(3.0) == NotImplemented
74+
assert (2).__mod__(3.0) == NotImplemented
75+
assert (2).__rmod__(3.0) == NotImplemented
6676

6777
assert 10 // 4 == 2
6878
assert -10 // 4 == -3

vm/src/obj/objint.rs

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,14 @@ fn inner_pow(int1: &PyInt, int2: &PyInt, vm: &VirtualMachine) -> PyResult {
138138
Ok(result)
139139
}
140140

141+
fn inner_mod(int1: &PyInt, int2: &PyInt, vm: &VirtualMachine) -> PyResult {
142+
if int2.value != BigInt::zero() {
143+
Ok(vm.ctx.new_int(&int1.value % &int2.value))
144+
} else {
145+
Err(vm.new_zero_division_error("integer modulo by zero".to_string()))
146+
}
147+
}
148+
141149
#[pyimpl]
142150
impl PyInt {
143151
#[pymethod(name = "__eq__")]
@@ -369,12 +377,18 @@ impl PyInt {
369377
#[pymethod(name = "__mod__")]
370378
fn mod_(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
371379
if objtype::isinstance(&other, &vm.ctx.int_type()) {
372-
let v2 = get_value(&other);
373-
if *v2 != BigInt::zero() {
374-
Ok(vm.ctx.new_int((&self.value) % v2))
375-
} else {
376-
Err(vm.new_zero_division_error("integer modulo by zero".to_string()))
377-
}
380+
let other = other.payload::<PyInt>().unwrap();
381+
inner_mod(self, &other, vm)
382+
} else {
383+
Ok(vm.ctx.not_implemented())
384+
}
385+
}
386+
387+
#[pymethod(name = "__rmod__")]
388+
fn rmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
389+
if objtype::isinstance(&other, &vm.ctx.int_type()) {
390+
let other = other.payload::<PyInt>().unwrap();
391+
inner_mod(&other, self, vm)
378392
} else {
379393
Ok(vm.ctx.not_implemented())
380394
}

0 commit comments

Comments
 (0)