{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module GHC.IO.BufferedIO (
BufferedIO(..),
readBuf, readBufNonBlocking, writeBuf, writeBufNonBlocking
) where
import GHC.Base
import GHC.Ptr
import Data.Word
import GHC.Num
import Data.Maybe
import GHC.IO.Device as IODevice
import GHC.IO.Device as RawIO
import GHC.IO.Buffer
class BufferedIO dev where
newBuffer :: dev -> BufferState -> IO (Buffer Word8)
fillReadBuffer :: dev -> Buffer Word8 -> IO (Int, Buffer Word8)
fillReadBuffer0 :: dev -> Buffer Word8 -> IO (Maybe Int, Buffer Word8)
emptyWriteBuffer :: dev -> Buffer Word8 -> IO (Buffer Word8)
emptyWriteBuffer _dev buf
= return buf{ bufL=0, bufR=0, bufState = WriteBuffer }
flushWriteBuffer :: dev -> Buffer Word8 -> IO (Buffer Word8)
flushWriteBuffer0 :: dev -> Buffer Word8 -> IO (Int, Buffer Word8)
readBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)
readBuf dev bbuf = do
let bytes = bufferAvailable bbuf
res <- withBuffer bbuf $ \ptr ->
RawIO.read dev (ptr `plusPtr` bufR bbuf) bytes
return (res, bbuf{ bufR = bufR bbuf + res })
readBufNonBlocking :: RawIO dev => dev -> Buffer Word8
-> IO (Maybe Int,
Buffer Word8)
readBufNonBlocking dev bbuf = do
let bytes = bufferAvailable bbuf
res <- withBuffer bbuf $ \ptr ->
IODevice.readNonBlocking dev (ptr `plusPtr` bufR bbuf) bytes
case res of
Nothing -> return (Nothing, bbuf)
Just n -> return (Just n, bbuf{ bufR = bufR bbuf + n })
writeBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Buffer Word8)
writeBuf dev bbuf = do
let bytes = bufferElems bbuf
withBuffer bbuf $ \ptr ->
IODevice.write dev (ptr `plusPtr` bufL bbuf) bytes
return bbuf{ bufL=0, bufR=0 }
writeBufNonBlocking :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)
writeBufNonBlocking dev bbuf = do
let bytes = bufferElems bbuf
res <- withBuffer bbuf $ \ptr ->
IODevice.writeNonBlocking dev (ptr `plusPtr` bufL bbuf) bytes
return (res, bufferAdjustL (bufL bbuf + res) bbuf)