Skip to content

Instantly share code, notes, and snippets.

@acowley
Created June 7, 2013 16:21
Show Gist options
  • Save acowley/5730486 to your computer and use it in GitHub Desktop.
Save acowley/5730486 to your computer and use it in GitHub Desktop.
Data.Vector.Storable and Data.ByteString
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad ((>=>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import Data.Vector.Storable (Vector)
import qualified Data.Vector.Storable as V
import Foreign.C.String (CStringLen)
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable(sizeOf))
packVector :: forall a b. Storable a => Vector a -> (CStringLen -> IO b) -> IO b
packVector v f = V.unsafeWith v aux
where aux p = f (castPtr p, V.length v * sizeOf (undefined::a))
unsafeWithByteString :: Storable a => Vector a -> (ByteString -> IO b) -> IO b
unsafeWithByteString v f = packVector v (B.unsafePackCStringLen >=> f)
toByteString :: Storable a => Vector a -> IO ByteString
toByteString = flip packVector B.packCStringLen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment