module Thrift.Transport.IOBuffer
( WriteBuffer
, newWriteBuffer
, writeBuf
, flushBuf
, ReadBuffer
, newReadBuffer
, fillBuf
, readBuf
, peekBuf
) where
import Data.ByteString.Lazy.Builder
import Data.Functor
import Data.IORef
import Data.Monoid
import Data.Word
import qualified Data.ByteString.Lazy as LBS
type WriteBuffer = IORef Builder
type ReadBuffer = IORef LBS.ByteString
newWriteBuffer :: IO WriteBuffer
newWriteBuffer = newIORef mempty
writeBuf :: WriteBuffer -> LBS.ByteString -> IO ()
writeBuf w s = modifyIORef w ( <> lazyByteString s)
flushBuf :: WriteBuffer -> IO LBS.ByteString
flushBuf w = do
buf <- readIORef w
writeIORef w mempty
return $ toLazyByteString buf
newReadBuffer :: IO ReadBuffer
newReadBuffer = newIORef mempty
fillBuf :: ReadBuffer -> LBS.ByteString -> IO ()
fillBuf = writeIORef
readBuf :: ReadBuffer -> Int -> IO LBS.ByteString
readBuf r n = do
bs <- readIORef r
let (hd, tl) = LBS.splitAt (fromIntegral n) bs
writeIORef r tl
return hd
peekBuf :: ReadBuffer -> IO (Maybe Word8)
peekBuf r = (fmap fst . LBS.uncons) <$> readIORef r