Created
June 7, 2013 16:21
-
-
Save acowley/5730486 to your computer and use it in GitHub Desktop.
Data.Vector.Storable and Data.ByteString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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