summaryrefslogtreecommitdiff
path: root/ByteStringUtil.hs
blob: 9711e0bf0598f7962e25bd24b7cf440bda250b34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module ByteStringUtil where

import Data.ByteString.Lazy.Internal
import Data.ByteString.Lazy as L
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)

readBigFile :: FilePath -> IO ByteString
readBigFile fname = do
    h <- openFile fname ReadMode
    hGetContentsN oneMeg h