I have an element of type Data.Vector.Unboxed.Vector Word32
. I want to convert that to a native JS TypedArray
(an Uint32Array
, specifically). I'm aware of toJsArray
and toJsValListOf
, but both functions deal with lists, not vectors, and are inefficient. How can I convert an unboxed Vector
directly to a JS TypedArray
?
1 Answer
I was able to solve this up to marshalling to an Int32Array
instead of an Uint32Array
; probably someone who has actually known GHCJS for more than the one hour I've put into this will be able to expand on this so that you get your Uint32Array
(or you can just make a hacked-up version of GHCJS.Buffer
that supports a getUint32Array
operation).
The idea is to get the ByteArray
underlying the Vector
representation, and then slice
it so that only the relevant portion remains:
import Data.Vector.Unboxed as V
import Data.Word
import qualified Data.Vector.Unboxed.Base as B
import qualified Data.Vector.Primitive as P
import GHCJS.Types
import qualified GHCJS.Buffer as Buffer
import JavaScript.TypedArray (Int32Array)
-- TODO: generalize this to all types that support unboxed vectors...
toI32Array :: Vector Word32 -> Int32Array
toI32Array (B.V_Word32 (P.Vector offset len bs)) =
js_slice offset (offset + len) $ Buffer.getInt32Array (Buffer.fromByteArray bs)
foreign import javascript unsafe "$3.slice($1, $2)" js_slice :: Int -> Int -> Int32Array -> Int32Array
-- should be
-- foreign import javascript unsafe "$3.slice($1, $2)" js_slice :: Int -> Int -> SomeTypedArray a m -> SomeTypedArray a m
-- but alas, JavaScript.TypedArray.Internal.Type is a hidden module
Here's some example code using it:
v :: Vector Word32
v = V.fromList [1, 2, 3]
foreign import javascript unsafe "console.debug($1);" js_debug :: JSVal -> IO ()
main = do
let v' = toI32Array v
js_debug $ jsval v'
If you look at the console in a browser, you can check that jsval v'
does indeed have type Int32Array
.
-
Cool! A bit too late for me, though - I ended up figuring I could just pass a ByteString's Ptr directly to JavaScript on the FFI. I then used the lib Spool to convert from unboxed vectors to bytestrings without copying. Dec 27, 2015 at 19:00
-
@Viclib, could you explain how you did that? I'm currently trying to figure out how to get a typed array from a bytestring and I'm having trouble. Mar 13, 2016 at 17:06
-
I explained. You have a Haskell ByteString, right? Send it to a JavaScript function (anything you write using the FFI) as an argument. Use
console.log
on it. You'll see the data is all there as different buffer types, you can just chose one. Mar 14, 2016 at 17:11 -
1@Viclib Is there an instance of
(IsJSVal ByteString)
somewhere that I need to be importing? You can't calljsval
onByteString
without it. Mar 14, 2016 at 20:43 -
... I really don't remember... this is the relevant code I wrote, though. I've looked at it, seems like like you just need to convert the ByteString to a CString with
B.useAsCString
.... Mar 14, 2016 at 21:19