Skip to content

Commit

Permalink
added: copying data directy from Onyx to JS through Uint8Array
Browse files Browse the repository at this point in the history
  • Loading branch information
brendanfh committed Mar 30, 2024
1 parent 297cadc commit 85e8f92
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core/js/foreign.onyx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ use core.alloc

__new_object :: () -> Value ---
__new_array :: () -> Value ---

__copy_to_js :: (arraybuf: Value, buf: [] u8) -> i32 ---
__copy_to_onyx :: (buf: [] u8, arraybuf: Value) -> i32 ---
}

// Func
Expand Down
26 changes: 26 additions & 0 deletions core/js/onyx.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,32 @@ Onyx.register_module("__syscall", instance => ({
const onyxmem = new Uint8Array(instance.memory.buffer)
onyxmem.set(encoded, outptr)
return encoded.length
},
__copy_to_js(a_ref, bufptr, buflen) {
const a = instance.load_value(a_ref)
if (!(a instanceof Uint8Array || a instanceof Uint8ClampedArray)) {
return -1
}

const onyxmem = new Uint8Array(instance.memory.buffer)
const copylen = Math.min(buflen, a.length)
const to_copy = onyxmem.subarray(bufptr, bufptr+copylen)
a.set(to_copy)

return copylen
},
__copy_to_onyx(bufptr, buflen, a_ref) {
const a = instance.load_value(a_ref)
if (!(a instanceof Uint8Array || a instanceof Uint8ClampedArray)) {
return -1
}

const onyxmem = new Uint8Array(instance.memory.buffer, bufptr)
const copylen = Math.min(buflen, a.length)
const to_copy = a.subarray(0, copylen)
onyxmem.set(to_copy)

return copylen
}
}))

17 changes: 17 additions & 0 deletions core/js/value.onyx
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,23 @@ Value.truthy :: (v: Value) -> bool {
}
}

#doc """
Copies data from a Uint8Array in JS to a buffer in Onyx.
Returns the number of bytes copied, or -1 if the value was not a Uint8Array.
"""
Value.copy_to_onyx :: (v: Value, buf: [] u8) -> i32 {
return __copy_to_onyx(buf, v);
}


#doc """
Copies data into a Uint8Array in JS from a buffer in Onyx.
Returns the number of bytes copied, or -1 if the value was not a Uint8Array.
"""
Value.copy_to_js :: (v: Value, buf: [] u8) -> i32 {
return __copy_to_js(v, buf);
}


#local
transform_args :: macro (args: [] any, $body: Code) {
Expand Down

0 comments on commit 85e8f92

Please sign in to comment.