packages feed

conduit-algorithms-0.0.8.1 / Data / Conduit / Algorithms / Storable.hs

{-|Module      : Data.Conduit.Algorithms.StorableCopyright   : 2018 Luis Pedro CoelhoLicense     : MITMaintainer  : luis@luispedro.orgHigher level async processing interfaces.-}{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}module Data.Conduit.Algorithms.Storable    ( writeStorableV    , readStorableV    ) whereimport qualified Data.ByteString as Bimport qualified Data.ByteString.Unsafe as BUimport qualified Data.Vector.Storable as VSimport qualified Data.Vector.Storable.Mutable as VSMimport Control.Monad.IO.Classimport Foreign.Ptrimport Foreign.Marshal.Utilsimport Foreign.Storableimport Control.Monad (when)import qualified Data.Conduit.List as CLimport qualified Data.Conduit.Combinators as CCimport qualified Data.Conduit as Cimport           Data.Conduit ((.|))-- | write a Storable vector---- This uses the same format as in-memory---- See 'readStorableV'writeStorableV :: forall m a. (MonadIO m, Monad m, Storable a) => C.Conduit (VS.Vector a) m B.ByteStringwriteStorableV = CL.mapM (liftIO. encodeStorable')    where        encodeStorable' :: Storable a => VS.Vector a -> IO B.ByteString        encodeStorable' v' = VS.unsafeWith v' $ \p ->                                    B.packCStringLen (castPtr p, VS.length v' * (sizeOf (undefined :: a)))-- | read a Storable vector---- This expects the same format as the in-memory vector---- See 'writeStorableV'readStorableV :: forall m a. (MonadIO m, Storable a) => Int -> C.ConduitM B.ByteString (VS.Vector a) m ()readStorableV nelems = CC.chunksOfE blockBytes .| parseBlocks    where        blockBytes = nelems * (sizeOf a')        a' :: a        a' = undefined        parseBlocks :: MonadIO m => C.Conduit B.ByteString m (VS.Vector a)        parseBlocks = C.awaitForever $ \bs -> do            let (n,rest) = B.length bs `divMod` sizeOf a'            r <- liftIO $ do                v <- VSM.new n                BU.unsafeUseAsCStringLen bs $ \(p, _) ->                    VSM.unsafeWith v $ \vp ->                        moveBytes (castPtr vp) p (n * sizeOf a')                VS.unsafeFreeze v            C.yield r            when (rest > 0) $ do                C.leftover (B.drop (n * sizeOf a') bs)