summaryrefslogtreecommitdiff
path: root/lib/ByteStringUtil.hs
blob: c6b509d5a405f0a2c29e666725158295986f1937 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module ByteStringUtil where

import Data.ByteString.Lazy.Internal
import Data.ByteString.Lazy
import qualified Data.ByteString as S
import System.IO
import System.IO.Unsafe

oneMeg :: Int
oneMeg = 1048576

hGetContentsN :: Int -> Handle -> IO ByteString
hGetContentsN kk h = lazyRead
  where
    k = kk - chunkOverhead
    lazyRead = unsafeInterleaveIO loop

    loop = do
        c <- S.hGetSome h k -- only blocks if there is no data available
        if S.null c
          then hClose h >> return Empty
          else do cs <- lazyRead
                  return (Chunk c cs)