Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create typed arrays from Go #379

Closed
s1na opened this issue Apr 7, 2022 · 3 comments
Closed

Create typed arrays from Go #379

s1na opened this issue Apr 7, 2022 · 3 comments
Labels

Comments

@s1na
Copy link

s1na commented Apr 7, 2022

Hello! I was wondering if it's possible to create a Uint8Array in Go and pass it to the JS code. I see there are functions like Runtime.newUint8Array but they are not exposed publicly. The workaround I came up for now is a JS function which takes in an array and returns a buffer and invoke that in Go, and pass the returned value again to JS which has unnecessary overhead.

@dop251
Copy link
Owner

dop251 commented Apr 7, 2022

Hi. You can do rt.New(rt.Get("Uint8Array")) (possibly cache rt.Get("Uint8Array") if you plan to do it many times and you don't override Uint8Array in your runtime).

@s1na
Copy link
Author

s1na commented Apr 8, 2022

Ok I managed to get it working with your suggestion, thanks. Closing this issue but please consider exposing those methods publicly.

@s1na s1na closed this as completed Apr 8, 2022
@dop251 dop251 added the question label Apr 8, 2022
@s1na
Copy link
Author

s1na commented Jun 23, 2022

Hey, just posting this for people who need to do the same thing:

func toBuf(vm *goja.Runtime, bufType goja.Value, val []byte) (goja.Value, error) {
      // bufType is cached `vm.Get("Uint8Array")`
     return vm.New(bufType, vm.ToValue(vm.NewArrayBuffer(val)))
}

Note by first casting to ArrayBuffer you'll avoid copying and get a significant speed-up.

And to get a buffer from JS:

func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value) ([]byte, error) {
    obj := buf.ToObject(vm)
    if !obj.Get("constructor").SameAs(bufType) {
        return nil, errors.New("invalid buffer")
    }
    b := obj.Get("buffer").Export().(goja.ArrayBuffer).Bytes()
    return b, nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants