module Codec.Archive.Common ( actFree
                            , actFreeCallback
                            , hmemcpy
                            ) where

import           Codec.Archive.Foreign
import           Codec.Archive.Monad    (ArchiveM, bracketM)
import           Control.Composition    ((.**))
import           Control.Monad          (void)
import           Control.Monad.IO.Class (MonadIO (..))
import           Foreign.C.Types        (CSize (..))
import           Foreign.Ptr

foreign import ccall memcpy :: Ptr a -- ^ Destination
                            -> Ptr b -- ^ Source
                            -> CSize -- ^ Size
                            -> IO (Ptr a) -- ^ Pointer to destination

hmemcpy :: Ptr a -> Ptr b -> CSize -> IO ()
hmemcpy :: Ptr a -> Ptr b -> CSize -> IO ()
hmemcpy = IO (Ptr a) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO (Ptr a) -> IO ())
-> (Ptr a -> Ptr b -> CSize -> IO (Ptr a))
-> Ptr a
-> Ptr b
-> CSize
-> IO ()
forall d e a b c.
(d -> e) -> (a -> b -> c -> d) -> a -> b -> c -> e
.** Ptr a -> Ptr b -> CSize -> IO (Ptr a)
forall a b. Ptr a -> Ptr b -> CSize -> IO (Ptr a)
memcpy

-- | Do something with an 'Archive' and then free it
actFree :: IO (Ptr Archive)
        -> (Ptr Archive -> ArchiveM a)
        -> ArchiveM a
actFree :: IO (Ptr Archive) -> (Ptr Archive -> ArchiveM a) -> ArchiveM a
actFree get :: IO (Ptr Archive)
get = IO (Ptr Archive)
-> (Ptr Archive -> IO ArchiveResult)
-> (Ptr Archive -> ArchiveM a)
-> ArchiveM a
forall a b c.
IO a -> (a -> IO b) -> (a -> ArchiveM c) -> ArchiveM c
bracketM IO (Ptr Archive)
get Ptr Archive -> IO ArchiveResult
archiveFree

actFreeCallback :: MonadIO m
                => (Ptr Archive -> m a)
                -> (Ptr Archive, IO ()) -- ^ 'Ptr' to an 'Archive' and an 'IO' action to clean up when done
                -> m a
actFreeCallback :: (Ptr Archive -> m a) -> (Ptr Archive, IO ()) -> m a
actFreeCallback fact :: Ptr Archive -> m a
fact (a :: Ptr Archive
a, freeAct :: IO ()
freeAct) = Ptr Archive -> m a
fact Ptr Archive
a m a -> m ArchiveResult -> m a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* IO ArchiveResult -> m ArchiveResult
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Ptr Archive -> IO ArchiveResult
archiveFree Ptr Archive
a) m a -> m () -> m a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO ()
freeAct