Skip to content

Commit c5b94a4

Browse files
authored
Merge pull request RustPython#408 from janczer/add_floats_div_mul
Add floats.{__truediv__, __mul__}
2 parents 3376808 + ba19732 commit c5b94a4

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

tests/snippets/floats.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,6 @@
1515
assert c >= a
1616
assert not a >= b
1717

18+
assert a + b == 2.5
19+
assert a - c == 0
20+
assert a / c == 1

vm/src/obj/objfloat.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,46 @@ fn float_pow(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
266266
}
267267
}
268268

269+
fn float_truediv(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
270+
arg_check!(
271+
vm,
272+
args,
273+
required = [(i, Some(vm.ctx.float_type())), (i2, None)]
274+
);
275+
let v1 = get_value(i);
276+
if objtype::isinstance(i2, &vm.ctx.float_type) {
277+
Ok(vm.ctx.new_float(v1 / get_value(i2)))
278+
} else if objtype::isinstance(i2, &vm.ctx.int_type) {
279+
Ok(vm
280+
.ctx
281+
.new_float(v1 / objint::get_value(i2).to_f64().unwrap()))
282+
} else {
283+
Err(vm.new_type_error(format!("Cannot divide {} and {}", i.borrow(), i2.borrow())))
284+
}
285+
}
286+
287+
fn float_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
288+
arg_check!(
289+
vm,
290+
args,
291+
required = [(i, Some(vm.ctx.float_type())), (i2, None)]
292+
);
293+
let v1 = get_value(i);
294+
if objtype::isinstance(i2, &vm.ctx.float_type) {
295+
Ok(vm.ctx.new_float(v1 * get_value(i2)))
296+
} else if objtype::isinstance(i2, &vm.ctx.int_type) {
297+
Ok(vm
298+
.ctx
299+
.new_float(v1 * objint::get_value(i2).to_f64().unwrap()))
300+
} else {
301+
Err(vm.new_type_error(format!(
302+
"Cannot multiply {} and {}",
303+
i.borrow(),
304+
i2.borrow()
305+
)))
306+
}
307+
}
308+
269309
pub fn init(context: &PyContext) {
270310
let float_type = &context.float_type;
271311

@@ -299,4 +339,10 @@ pub fn init(context: &PyContext) {
299339
"__doc__",
300340
context.new_str(float_doc.to_string()),
301341
);
342+
context.set_attr(
343+
&float_type,
344+
"__truediv__",
345+
context.new_rustfunc(float_truediv),
346+
);
347+
context.set_attr(&float_type, "__mul__", context.new_rustfunc(float_mul));
302348
}

0 commit comments

Comments
 (0)