Skip to content

Commit 8e5073e

Browse files
committed
Convert bytes and bytearrays to Uint8Arrays
1 parent 634571f commit 8e5073e

1 file changed

Lines changed: 29 additions & 16 deletions

File tree

wasm/lib/src/convert.rs

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use js_sys::{Array, ArrayBuffer, Object, Reflect, Uint8Array};
2+
use rustpython_vm::obj::{objbytes, objtype};
23
use rustpython_vm::pyobject::{self, PyFuncArgs, PyObjectRef, PyResult};
34
use rustpython_vm::VirtualMachine;
45
use vm_class::{AccessibleVM, WASMVirtualMachine};
@@ -16,10 +17,10 @@ pub fn js_py_typeerror(vm: &mut VirtualMachine, js_err: JsValue) -> PyObjectRef
1617

1718
pub fn py_to_js(vm: &mut VirtualMachine, py_obj: PyObjectRef) -> JsValue {
1819
if let Some(ref wasm_id) = vm.wasm_id {
19-
let wasm_vm = WASMVirtualMachine {
20-
id: wasm_id.clone(),
21-
};
22-
if rustpython_vm::obj::objtype::isinstance(&py_obj, &vm.ctx.function_type()) {
20+
if objtype::isinstance(&py_obj, &vm.ctx.function_type()) {
21+
let wasm_vm = WASMVirtualMachine {
22+
id: wasm_id.clone(),
23+
};
2324
let closure =
2425
move |args: Option<Array>, kwargs: Option<Object>| -> Result<JsValue, JsValue> {
2526
let py_obj = py_obj.clone();
@@ -55,19 +56,31 @@ pub fn py_to_js(vm: &mut VirtualMachine, py_obj: PyObjectRef) -> JsValue {
5556
return func;
5657
}
5758
}
58-
let dumps = rustpython_vm::import::import(
59-
vm,
60-
std::path::PathBuf::default(),
61-
"json",
62-
&Some("dumps".into()),
63-
)
64-
.expect("Couldn't get json.dumps function");
65-
match vm.invoke(dumps, pyobject::PyFuncArgs::new(vec![py_obj], vec![])) {
66-
Ok(value) => {
67-
let json = vm.to_pystr(&value).unwrap();
68-
js_sys::JSON::parse(&json).unwrap_or(JsValue::UNDEFINED)
59+
if objtype::isinstance(&py_obj, &vm.ctx.bytes_type())
60+
|| objtype::isinstance(&py_obj, &vm.ctx.bytearray_type())
61+
{
62+
let bytes = objbytes::get_value(&py_obj);
63+
let arr = Uint8Array::new_with_length(bytes.len() as u32);
64+
for (i, byte) in bytes.iter().enumerate() {
65+
Reflect::set(&arr, &(i as u32).into(), &(*byte).into())
66+
.expect("setting Uint8Array value failed");
67+
}
68+
arr.into()
69+
} else {
70+
let dumps = rustpython_vm::import::import(
71+
vm,
72+
std::path::PathBuf::default(),
73+
"json",
74+
&Some("dumps".into()),
75+
)
76+
.expect("Couldn't get json.dumps function");
77+
match vm.invoke(dumps, pyobject::PyFuncArgs::new(vec![py_obj], vec![])) {
78+
Ok(value) => {
79+
let json = vm.to_pystr(&value).unwrap();
80+
js_sys::JSON::parse(&json).unwrap_or(JsValue::UNDEFINED)
81+
}
82+
Err(_) => JsValue::UNDEFINED,
6983
}
70-
Err(_) => JsValue::UNDEFINED,
7184
}
7285
}
7386

0 commit comments

Comments
 (0)