mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-09 22:49:57 +09:00
Add floats.{__truediv__, __mul__}
This commit is contained in:
@@ -15,3 +15,6 @@ assert b >= a
|
||||
assert c >= a
|
||||
assert not a >= b
|
||||
|
||||
assert a + b == 2.5
|
||||
assert a - c == 0
|
||||
assert a / c == 1
|
||||
|
||||
@@ -266,6 +266,46 @@ fn float_pow(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
}
|
||||
}
|
||||
|
||||
fn float_truediv(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
arg_check!(
|
||||
vm,
|
||||
args,
|
||||
required = [(i, Some(vm.ctx.float_type())), (i2, None)]
|
||||
);
|
||||
let v1 = get_value(i);
|
||||
if objtype::isinstance(i2, &vm.ctx.float_type) {
|
||||
Ok(vm
|
||||
.ctx
|
||||
.new_float(v1 / get_value(i2)))
|
||||
} else if objtype::isinstance(i2, &vm.ctx.int_type) {
|
||||
Ok(vm
|
||||
.ctx
|
||||
.new_float(v1 / objint::get_value(i2).to_f64().unwrap()))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!("Cannot divide {} and {}", i.borrow(), i2.borrow())))
|
||||
}
|
||||
}
|
||||
|
||||
fn float_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
arg_check!(
|
||||
vm,
|
||||
args,
|
||||
required = [(i, Some(vm.ctx.float_type())), (i2, None)]
|
||||
);
|
||||
let v1 = get_value(i);
|
||||
if objtype::isinstance(i2, &vm.ctx.float_type) {
|
||||
Ok(vm
|
||||
.ctx
|
||||
.new_float(v1 * get_value(i2)))
|
||||
} else if objtype::isinstance(i2, &vm.ctx.int_type) {
|
||||
Ok(vm
|
||||
.ctx
|
||||
.new_float(v1 * objint::get_value(i2).to_f64().unwrap()))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!("Cannot divide {} and {}", i.borrow(), i2.borrow())))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(context: &PyContext) {
|
||||
let float_type = &context.float_type;
|
||||
|
||||
@@ -299,4 +339,6 @@ pub fn init(context: &PyContext) {
|
||||
"__doc__",
|
||||
context.new_str(float_doc.to_string()),
|
||||
);
|
||||
context.set_attr(&float_type, "__truediv__", context.new_rustfunc(float_truediv));
|
||||
context.set_attr(&float_type, "__mul__", context.new_rustfunc(float_mul));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user