Search code examples
javascripthaskellghcjs

How do you convert from an Unboxed Vector to a JS TypedArray on GHCJS?


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?


Solution

  • 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.