How to convert between ByteString and Storable Vector?

前端 未结 2 1194
清歌不尽
清歌不尽 2021-02-13 17:50

What is the best way to convert between Storable.Vector Word8 and a strict ByteString?

Of course a non-copying (no-op) way would be most apprec

2条回答
  •  -上瘾入骨i
    2021-02-13 18:45

    byteStringToVector :: (Storable a) => BS.ByteString -> V.Vector a
    byteStringToVector bs = vec where
        vec = V.unsafeFromForeignPtr (castForeignPtr fptr) (scale off) (scale len)
        (fptr, off, len) = BS.toForeignPtr bs
        scale = (`div` sizeOfElem vec)
    
    sizeOfElem vec = sizeOf (undefined `asTypeOf` V.head vec)
    

    http://hackage.haskell.org/packages/archive/spool/0.1/doc/html/Data-Vector-Storable-ByteString.html

提交回复
热议问题