ruby.wasm icon indicating copy to clipboard operation
ruby.wasm copied to clipboard

Port `arraybuffer` to ruby

Open krmbn0576 opened this issue 2 years ago • 6 comments

require "js"

response = JS.global.fetch("<dumped buffer's url>").await
puts response[:status]

arraybuffer = response.arrayBuffer.await

# Expected goal:
#   Marshal.load(arraybuffer)

some byte arrays need to port ruby (typically generated by Marshal.dump), but no fast way

# Correct but too slow way:
uint8array = JS.global[:Uint8Array].new(arraybuffer)
Marshal.load(uint8array.to_a.map(&:to_i).pack("C*")) # Especially the slow JS::Object#to_i on each byte.

krmbn0576 avatar Dec 15 '23 14:12 krmbn0576

Hi @kateinoigakukun , what is the status of this issue? Is more detailed information required to understand the issue? Or did you understand the issue, but decided it was not important? Is my contribution to the issue welcome or not?

krmbn0576 avatar Dec 21 '23 14:12 krmbn0576

I think what you need is JavaScript's ArrayBuffer <-> Ruby String (ASCII_8BIT) conversion or just add some methods to JS::Object to behave like IO. But I'm still not sure what kind of design is good to be Rubyish.

If you have any particular idea or implementation, I'm open to discussing it.

kateinoigakukun avatar Dec 21 '23 15:12 kateinoigakukun

Hmmm certainly worth thinking about. I'm not a Rubyist, so it's not a brilliant idea by any means, but I've thought of two ways.

  1. specialize ArrayBuffer#to_s and return data converted to ASCII_8BIT

Of course this is destructive, but no one will spare the old behavior since the current to_s always returns [object ArrayBuffer] and is useless.

  1. create a new JS.fetch function and convert to ASCII_8BIT if to_rstr: true

Here is how to use it.

ascii_8bit = JS.fetch("<url>", to_rstr: true).await

krmbn0576 avatar Dec 21 '23 22:12 krmbn0576

Thank you for your idea. I'll continue exploring ways including yours.

kateinoigakukun avatar Dec 22 '23 01:12 kateinoigakukun

It seems String class has String#b method to convert the self content to ASCII-8BIT string. JS::Object#b might be a considerable option?

kateinoigakukun avatar Dec 22 '23 05:12 kateinoigakukun

It might not be bad. However, String#b is probably just String#force_encoding("ASCII-8BIT") internally. Note that the nature of this issue is conversion, which is more like String#encode, so the nuance may be a bit different.

krmbn0576 avatar Dec 22 '23 06:12 krmbn0576