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

笑着哭i 提交于 2019-12-07 10:22:28

问题


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:


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.



来源:https://stackoverflow.com/questions/34406652/how-do-you-convert-from-an-unboxed-vector-to-a-js-typedarray-on-ghcjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!