Convert a vector to a byte string in Haskell

I am puzzled by how I can convert the Data.Vector.Storable vector to a ByteString. I suppose I'm missing something fairly obvious.

I need to convert it to ByteString because I want to send it over the network using Network.Socket.ByteString, and it seems to be the most efficient data structure.

How to write code to write a function

writeToByteString :: Vector Int -> ByteString
writeToByteString v = 

Many thanks.

+4
source share
1 answer

It depends on what you really want to achieve. As bheklilr mentioned, the view Intis platform specific.

But the stored vector under the hood is part of the memory. To get content, use unsafeToForeignPtr0. Here is an example:

import qualified Data.Vector.Storable as V
import qualified Data.ByteString as BS

import Foreign

main :: IO ()
main = do
  let v = V.generate 10 id :: V.Vector Int
      (fptr, len) = V.unsafeToForeignPtr0 v
  print v
  bs <- withForeignPtr fptr $ \ptr ->
    BS.packCStringLen (castPtr ptr, len * sizeOf (undefined :: Int))
  print $ BS.unpack bs

Output:

fromList [0,1,2,3,4,5,6,7,8,9]
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0]
+2
source

Source: https://habr.com/ru/post/1532482/


All Articles