Add _operator module

This commit is contained in:
coolreader18
2019-12-29 11:40:05 -06:00
committed by Noah
parent fc3ac169d0
commit c65dc336f5
2 changed files with 26 additions and 0 deletions

View File

@@ -16,6 +16,7 @@ mod json;
mod keyword;
mod marshal;
mod math;
mod operator;
mod platform;
mod pystruct;
mod random;
@@ -74,6 +75,7 @@ pub fn get_module_inits() -> HashMap<String, StdlibInitFunc> {
"json".to_string() => Box::new(json::make_module),
"marshal".to_string() => Box::new(marshal::make_module),
"math".to_string() => Box::new(math::make_module),
"_operator".to_string() => Box::new(operator::make_module),
"platform".to_string() => Box::new(platform::make_module),
"regex_crate".to_string() => Box::new(re::make_module),
"random".to_string() => Box::new(random::make_module),

24
vm/src/stdlib/operator.rs Normal file
View File

@@ -0,0 +1,24 @@
use crate::function::OptionalArg;
use crate::obj::{objiter, objtype};
use crate::pyobject::{PyObjectRef, PyResult, TypeProtocol};
use crate::VirtualMachine;
fn operator_length_hint(obj: PyObjectRef, default: OptionalArg, vm: &VirtualMachine) -> PyResult {
let default = default.unwrap_or_else(|| vm.new_int(0));
if !objtype::isinstance(&default, &vm.ctx.types.int_type) {
return Err(vm.new_type_error(format!(
"'{}' type cannot be interpreted as an integer",
default.class().name
)));
}
let hint = objiter::length_hint(vm, obj)?
.map(|i| vm.new_int(i))
.unwrap_or(default);
Ok(hint)
}
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
py_module!(vm, "_operator", {
"length_hint" => vm.ctx.new_rustfunc(operator_length_hint),
})
}