module Network.MoHWS.ByteString where
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import qualified System.IO as IO
import Control.Monad (liftM2, )
import System.IO.Unsafe (unsafeInterleaveIO, )
hGetContentsN :: Int -> IO.Handle -> IO L.ByteString
hGetContentsN k h =
let loop = unsafeInterleaveIO $ do
eof <- IO.hIsEOF h
if eof
then return L.empty
else
do liftM2
(\c -> L.append (L.fromChunks [c]))
(S.hGet h k) loop
in loop
hGetContentsNonBlockingN :: Int -> IO.Handle -> IO L.ByteString
hGetContentsNonBlockingN k h =
let lazyRead = unsafeInterleaveIO loop
loop = do
c <- S.hGetNonBlocking h k
if S.null c
then do eof <- IO.hIsEOF h
if eof
then return L.empty
else IO.hWaitForInput h (-1) >> loop
else fmap (L.append $ L.fromChunks [c]) lazyRead
in lazyRead
hGetChars :: IO.Handle -> Int -> IO String
hGetChars h n = fmap L.unpack $ L.hGet h n