-- FIXME rename module
module Util.BufferedIOx
    ( BufferedIOx(..)
    , runGetBuffered
    , runPutBuffered
    , module Util.Binary
    ) where

import           Control.Monad.IO.Class
import           Data.Binary
import qualified Data.ByteString        as BS ( ByteString )
import qualified Data.ByteString.Lazy   as LBS ( ByteString )
import           Util.Binary
import           Util.IOExtra

class BufferedIOx a where
    readBuffered :: (MonadIO m) => a -> Int -> m BS.ByteString
    unreadBuffered :: (MonadIO m) => a -> BS.ByteString -> m ()
    writeBuffered :: (MonadIO m) => a -> LBS.ByteString -> m ()
    closeBuffered :: (MonadIO m) => a -> m ()

runGetBuffered :: (MonadIO m, BufferedIOx s, Binary a, MonadMask m, MonadLogger m) => s -> m a
runGetBuffered :: s -> m a
runGetBuffered s
s =
  m (Either BinaryGetError a) -> m a
forall (m :: * -> *) e r.
(HasCallStack, MonadMask m, MonadLogger m, Exception e) =>
m (Either e r) -> m r
throwLeftM ((Int -> m ByteString)
-> (ByteString -> m ()) -> Get a -> m (Either BinaryGetError a)
forall (m :: * -> *) a.
(HasCallStack, Monad m) =>
(Int -> m ByteString)
-> (ByteString -> m ()) -> Get a -> m (Either BinaryGetError a)
runGetA (IO ByteString -> m ByteString
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ByteString -> m ByteString)
-> (Int -> IO ByteString) -> Int -> m ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. s -> Int -> IO ByteString
forall a (m :: * -> *).
(BufferedIOx a, MonadIO m) =>
a -> Int -> m ByteString
readBuffered s
s) (IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> (ByteString -> IO ()) -> ByteString -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. s -> ByteString -> IO ()
forall a (m :: * -> *).
(BufferedIOx a, MonadIO m) =>
a -> ByteString -> m ()
unreadBuffered s
s) Get a
forall t. Binary t => Get t
get)

runPutBuffered :: (MonadIO m, BufferedIOx s, Binary a) => s -> a -> m ()
runPutBuffered :: s -> a -> m ()
runPutBuffered s
s = (ByteString -> m ()) -> Put -> m ()
forall (m :: * -> *).
HasCallStack =>
(ByteString -> m ()) -> Put -> m ()
runPutA (IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> (ByteString -> IO ()) -> ByteString -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. s -> ByteString -> IO ()
forall a (m :: * -> *).
(BufferedIOx a, MonadIO m) =>
a -> ByteString -> m ()
writeBuffered s
s) (Put -> m ()) -> (a -> Put) -> a -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Put
forall t. Binary t => t -> Put
put