forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwasm_builtins.rs
More file actions
40 lines (35 loc) · 1.36 KB
/
wasm_builtins.rs
File metadata and controls
40 lines (35 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//! Builtin function specific to WASM build.
//!
//! This is required because some feature like I/O works differently in the browser comparing to
//! desktop.
//! Implements functions listed here: https://docs.python.org/3/library/builtins.html.
use web_sys::{self, console};
use rustpython_vm::obj::objstr::PyStringRef;
use rustpython_vm::pyobject::{PyObjectRef, PyResult};
use rustpython_vm::VirtualMachine;
pub(crate) fn window() -> web_sys::Window {
web_sys::window().expect("Window to be available")
}
pub fn sys_stdout_write_console(data: &str, _vm: &VirtualMachine) -> PyResult<()> {
console::log_1(&data.into());
Ok(())
}
pub fn make_stdout_object(
vm: &VirtualMachine,
write_f: impl Fn(&str, &VirtualMachine) -> PyResult<()> + Send + Sync + 'static,
) -> PyObjectRef {
let ctx = &vm.ctx;
let write_method = ctx.new_method(
move |_self: PyObjectRef, data: PyStringRef, vm: &VirtualMachine| -> PyResult<()> {
write_f(data.as_str(), vm)
},
);
let flush_method = ctx.new_method(|_self: PyObjectRef| {});
// there's not really any point to storing this class so that there's a consistent type object,
// we just want a half-decent repr() output
let cls = py_class!(ctx, "JSStdout", vm.ctx.object(), {
"write" => write_method,
"flush" => flush_method,
});
ctx.new_base_object(cls, None)
}