Skip to content

Commit 921efd4

Browse files
committed
Switch to using json.dumps for py_to_js()
1 parent 2ae1df5 commit 921efd4

1 file changed

Lines changed: 14 additions & 44 deletions

File tree

wasm/src/lib.rs

Lines changed: 14 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -18,50 +18,20 @@ fn py_str_err(vm: &mut VirtualMachine, py_err: &PyObjectRef) -> String {
1818
.unwrap_or_else(|_| "Error, and error getting error message".into())
1919
}
2020

21-
fn py_to_js(vm: &mut VirtualMachine, py_obj: &PyObjectRef) -> JsValue {
22-
use pyobject::PyObjectKind;
23-
let py_obj = py_obj.borrow();
24-
match py_obj.kind {
25-
PyObjectKind::String { ref value } => value.into(),
26-
PyObjectKind::Integer { ref value } => {
27-
if let Some(ref typ) = py_obj.typ {
28-
if typ.is(&vm.ctx.bool_type()) {
29-
let out_bool = value == &BigInt::new(num_bigint::Sign::Plus, vec![1]);
30-
return out_bool.into();
31-
}
32-
}
33-
let int = vm.ctx.new_int(value.clone());
34-
rustpython_vm::obj::objfloat::make_float(vm, &int)
35-
.unwrap()
36-
.into()
37-
}
38-
PyObjectKind::Float { ref value } => JsValue::from_f64(*value),
39-
PyObjectKind::Bytes { ref value } => {
40-
let arr = js_sys::Uint8Array::new(&JsValue::from(value.len() as u32));
41-
for (i, byte) in value.iter().enumerate() {
42-
console::log_1(&JsValue::from(i as u32));
43-
js_sys::Reflect::set(&arr, &JsValue::from(i as u32), &JsValue::from(*byte))
44-
.unwrap();
45-
}
46-
arr.into()
47-
}
48-
PyObjectKind::Sequence { ref elements } => {
49-
let arr = js_sys::Array::new();
50-
for val in elements {
51-
arr.push(&py_to_js(vm, val));
52-
}
53-
arr.into()
54-
}
55-
PyObjectKind::Dict { ref elements } => {
56-
let obj = js_sys::Object::new();
57-
for (key, (_, val)) in elements {
58-
js_sys::Reflect::set(&obj, &key.into(), &py_to_js(vm, val))
59-
.expect("couldn't set property of object");
60-
}
61-
obj.into()
21+
fn py_to_js(vm: &mut VirtualMachine, py_obj: PyObjectRef) -> JsValue {
22+
let dumps = rustpython_vm::import::import(
23+
vm,
24+
std::path::PathBuf::default(),
25+
"json",
26+
&Some("dumps".into()),
27+
)
28+
.expect("Couldn't get json.dumps function");
29+
match vm.invoke(dumps, pyobject::PyFuncArgs::new(vec![py_obj], vec![])) {
30+
Ok(value) => {
31+
let json = vm.to_pystr(&value).unwrap();
32+
js_sys::JSON::parse(&json).unwrap_or(JsValue::UNDEFINED)
6233
}
63-
PyObjectKind::None => JsValue::UNDEFINED,
64-
_ => JsValue::UNDEFINED,
34+
Err(_) => JsValue::UNDEFINED,
6535
}
6636
}
6737

@@ -91,7 +61,7 @@ pub fn eval_py(source: &str) -> Result<JsValue, JsValue> {
9161
);
9262

9363
eval(&mut vm, source)
94-
.map(|value| py_to_js(&mut vm, &value))
64+
.map(|value| py_to_js(&mut vm, value))
9565
.map_err(|err| py_str_err(&mut vm, &err).into())
9666
}
9767

0 commit comments

Comments
 (0)