module Data.Packer.IO
( runPackingIO
, runUnpackingIO
, tryUnpackingIO
) where
import Data.Packer.Internal
import Data.Packer.Unsafe
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as B (ByteString(..), mallocByteString, toForeignPtr)
import Foreign.ForeignPtr
import qualified Control.Exception as E
runUnpackingIO :: ByteString -> Unpacking a -> IO a
runUnpackingIO bs action = runUnpackingAt fptr o len action
where (fptr,o,len) = B.toForeignPtr bs
tryUnpackingIO :: ByteString -> Unpacking a -> IO (Either E.SomeException a)
tryUnpackingIO bs action = E.try $ runUnpackingIO bs action
runPackingIO :: Int -> Packing a -> IO (a, ByteString)
runPackingIO sz action = createUptoN sz $ \ptr -> runPackingAt ptr sz action
where
createUptoN l f = do fp <- B.mallocByteString l
(a, l') <- withForeignPtr fp $ \p -> f p
return $! (,) a $! B.PS fp 0 l'