Skip to content

Port arraybuffer to ruby #342

Open
@krmbn0576

Description

@krmbn0576
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.

Activity

krmbn0576

krmbn0576 commented on Dec 21, 2023

@krmbn0576
ContributorAuthor

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?

kateinoigakukun

kateinoigakukun commented on Dec 21, 2023

@kateinoigakukun
Member

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.

krmbn0576

krmbn0576 commented on Dec 21, 2023

@krmbn0576
ContributorAuthor

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
kateinoigakukun

kateinoigakukun commented on Dec 22, 2023

@kateinoigakukun
Member

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

kateinoigakukun

kateinoigakukun commented on Dec 22, 2023

@kateinoigakukun
Member

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?

krmbn0576

krmbn0576 commented on Dec 22, 2023

@krmbn0576
ContributorAuthor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @kateinoigakukun@krmbn0576

      Issue actions

        Port `arraybuffer` to ruby · Issue #342 · ruby/ruby.wasm