Skip to content

Commit c65dc33

Browse files
committed
Add _operator module
1 parent fc3ac16 commit c65dc33

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

vm/src/stdlib/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ mod json;
1616
mod keyword;
1717
mod marshal;
1818
mod math;
19+
mod operator;
1920
mod platform;
2021
mod pystruct;
2122
mod random;
@@ -74,6 +75,7 @@ pub fn get_module_inits() -> HashMap<String, StdlibInitFunc> {
7475
"json".to_string() => Box::new(json::make_module),
7576
"marshal".to_string() => Box::new(marshal::make_module),
7677
"math".to_string() => Box::new(math::make_module),
78+
"_operator".to_string() => Box::new(operator::make_module),
7779
"platform".to_string() => Box::new(platform::make_module),
7880
"regex_crate".to_string() => Box::new(re::make_module),
7981
"random".to_string() => Box::new(random::make_module),

vm/src/stdlib/operator.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
use crate::function::OptionalArg;
2+
use crate::obj::{objiter, objtype};
3+
use crate::pyobject::{PyObjectRef, PyResult, TypeProtocol};
4+
use crate::VirtualMachine;
5+
6+
fn operator_length_hint(obj: PyObjectRef, default: OptionalArg, vm: &VirtualMachine) -> PyResult {
7+
let default = default.unwrap_or_else(|| vm.new_int(0));
8+
if !objtype::isinstance(&default, &vm.ctx.types.int_type) {
9+
return Err(vm.new_type_error(format!(
10+
"'{}' type cannot be interpreted as an integer",
11+
default.class().name
12+
)));
13+
}
14+
let hint = objiter::length_hint(vm, obj)?
15+
.map(|i| vm.new_int(i))
16+
.unwrap_or(default);
17+
Ok(hint)
18+
}
19+
20+
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
21+
py_module!(vm, "_operator", {
22+
"length_hint" => vm.ctx.new_rustfunc(operator_length_hint),
23+
})
24+
}

0 commit comments

Comments
 (0)