1 {-# OPTIONS_GHC -XNoImplicitPrelude -#include "HsBase.h" #-}
2 {-# OPTIONS_HADDOCK hide #-}
6 -----------------------------------------------------------------------------
9 -- Copyright : (c) The University of Glasgow, 1992-2001
10 -- License : see libraries/base/LICENSE
12 -- Maintainer : libraries@haskell.org
13 -- Stability : internal
14 -- Portability : non-portable
16 -- String I\/O functions
18 -----------------------------------------------------------------------------
22 hWaitForInput, hGetChar, hGetLine, hGetContents, hPutChar, hPutStr,
23 commitBuffer', -- hack, see below
24 hGetcBuffered, -- needed by ghc/compiler/utils/StringBuffer.lhs
25 hGetBuf, hGetBufNonBlocking, hPutBuf, hPutBufNonBlocking, slurpFile,
35 import System.IO.Error
38 import System.Posix.Internals
43 import GHC.Handle -- much of the real stuff is in here
49 #ifdef mingw32_HOST_OS
53 -- ---------------------------------------------------------------------------
54 -- Simple input operations
56 -- If hWaitForInput finds anything in the Handle's buffer, it
57 -- immediately returns. If not, it tries to read from the underlying
58 -- OS handle. Notice that for buffered Handles connected to terminals
59 -- this means waiting until a complete line is available.
61 -- | Computation 'hWaitForInput' @hdl t@
62 -- waits until input is available on handle @hdl@.
63 -- It returns 'True' as soon as input is available on @hdl@,
64 -- or 'False' if no input is available within @t@ milliseconds.
66 -- If @t@ is less than zero, then @hWaitForInput@ waits indefinitely.
68 -- This operation may fail with:
70 -- * 'isEOFError' if the end of file has been reached.
72 -- NOTE for GHC users: unless you use the @-threaded@ flag,
73 -- @hWaitForInput t@ where @t >= 0@ will block all other Haskell
74 -- threads for the duration of the call. It behaves like a
75 -- @safe@ foreign call in this respect.
77 hWaitForInput :: Handle -> Int -> IO Bool
78 hWaitForInput h msecs = do
79 wantReadableHandle "hWaitForInput" h $ \ handle_ -> do
80 let ref = haBuffer handle_
83 if not (bufferEmpty buf)
88 then do buf' <- fillReadBuffer (haFD handle_) True
89 (haIsStream handle_) buf
92 else do r <- throwErrnoIfMinus1Retry "hWaitForInput" $
93 fdReady (haFD handle_) 0 {- read -}
95 (fromIntegral $ fromEnum $ haIsStream handle_)
96 if r /= 0 then do -- Call hLookAhead' to throw an EOF
97 -- exception if appropriate
102 foreign import ccall safe "fdReady"
103 fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
105 -- ---------------------------------------------------------------------------
108 -- | Computation 'hGetChar' @hdl@ reads a character from the file or
109 -- channel managed by @hdl@, blocking until a character is available.
111 -- This operation may fail with:
113 -- * 'isEOFError' if the end of file has been reached.
115 hGetChar :: Handle -> IO Char
117 wantReadableHandle "hGetChar" handle $ \handle_ -> do
119 let fd = haFD handle_
120 ref = haBuffer handle_
123 if not (bufferEmpty buf)
124 then hGetcBuffered fd ref buf
128 case haBufferMode handle_ of
130 new_buf <- fillReadBuffer fd True (haIsStream handle_) buf
131 hGetcBuffered fd ref new_buf
132 BlockBuffering _ -> do
133 new_buf <- fillReadBuffer fd True (haIsStream handle_) buf
135 -- don't wait for a completely full buffer.
136 hGetcBuffered fd ref new_buf
138 -- make use of the minimal buffer we already have
140 r <- readRawBuffer "hGetChar" fd (haIsStream handle_) raw 0 1
143 else do (c,_) <- readCharFromBuffer raw 0
146 hGetcBuffered fd ref buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w }
147 = do (c,r) <- readCharFromBuffer b r
148 let new_buf | r == w = buf{ bufRPtr=0, bufWPtr=0 }
149 | otherwise = buf{ bufRPtr=r }
150 writeIORef ref new_buf
153 -- ---------------------------------------------------------------------------
156 -- ToDo: the unbuffered case is wrong: it doesn't lock the handle for
159 -- | Computation 'hGetLine' @hdl@ reads a line from the file or
160 -- channel managed by @hdl@.
162 -- This operation may fail with:
164 -- * 'isEOFError' if the end of file is encountered when reading
165 -- the /first/ character of the line.
167 -- If 'hGetLine' encounters end-of-file at any other point while reading
168 -- in a line, it is treated as a line terminator and the (partial)
171 hGetLine :: Handle -> IO String
173 m <- wantReadableHandle "hGetLine" h $ \ handle_ -> do
174 case haBufferMode handle_ of
175 NoBuffering -> return Nothing
177 l <- hGetLineBuffered handle_
179 BlockBuffering _ -> do
180 l <- hGetLineBuffered handle_
183 Nothing -> hGetLineUnBuffered h
186 hGetLineBuffered :: Handle__ -> IO String
187 hGetLineBuffered handle_ = do
188 let ref = haBuffer handle_
190 hGetLineBufferedLoop handle_ ref buf []
192 hGetLineBufferedLoop :: Handle__ -> IORef Buffer -> Buffer -> [String]
194 hGetLineBufferedLoop handle_ ref
195 buf@Buffer{ bufRPtr=r, bufWPtr=w, bufBuf=raw } xss =
197 -- find the end-of-line character, if there is one
199 | r == w = return (False, w)
201 (c,r') <- readCharFromBuffer raw r
203 then return (True, r) -- NB. not r': don't include the '\n'
206 (eol, off) <- loop raw r
209 puts ("hGetLineBufferedLoop: r=" ++ show r ++ ", w=" ++ show w ++ ", off=" ++ show off ++ "\n")
212 xs <- unpack raw r off
214 -- if eol == True, then off is the offset of the '\n'
215 -- otherwise off == w and the buffer is now empty.
217 then do if (w == off + 1)
218 then writeIORef ref buf{ bufRPtr=0, bufWPtr=0 }
219 else writeIORef ref buf{ bufRPtr = off + 1 }
220 return (concat (reverse (xs:xss)))
222 maybe_buf <- maybeFillReadBuffer (haFD handle_) True (haIsStream handle_)
223 buf{ bufWPtr=0, bufRPtr=0 }
225 -- Nothing indicates we caught an EOF, and we may have a
226 -- partial line to return.
228 writeIORef ref buf{ bufRPtr=0, bufWPtr=0 }
229 let str = concat (reverse (xs:xss))
234 hGetLineBufferedLoop handle_ ref new_buf (xs:xss)
237 maybeFillReadBuffer fd is_line is_stream buf
239 (do buf <- fillReadBuffer fd is_line is_stream buf
242 (\e -> do if isEOFError e
247 unpack :: RawBuffer -> Int -> Int -> IO [Char]
248 unpack buf r 0 = return ""
249 unpack buf (I# r) (I# len) = IO $ \s -> unpack [] (len -# 1#) s
252 | i <# r = (# s, acc #)
254 case readCharArray# buf i s of
255 (# s, ch #) -> unpack (C# ch : acc) (i -# 1#) s
258 hGetLineUnBuffered :: Handle -> IO String
259 hGetLineUnBuffered h = do
272 if isEOFError err then
282 -- -----------------------------------------------------------------------------
285 -- hGetContents on a DuplexHandle only affects the read side: you can
286 -- carry on writing to it afterwards.
288 -- | Computation 'hGetContents' @hdl@ returns the list of characters
289 -- corresponding to the unread portion of the channel or file managed
290 -- by @hdl@, which is put into an intermediate state, /semi-closed/.
291 -- In this state, @hdl@ is effectively closed,
292 -- but items are read from @hdl@ on demand and accumulated in a special
293 -- list returned by 'hGetContents' @hdl@.
295 -- Any operation that fails because a handle is closed,
296 -- also fails if a handle is semi-closed. The only exception is 'hClose'.
297 -- A semi-closed handle becomes closed:
299 -- * if 'hClose' is applied to it;
301 -- * if an I\/O error occurs when reading an item from the handle;
303 -- * or once the entire contents of the handle has been read.
305 -- Once a semi-closed handle becomes closed, the contents of the
306 -- associated list becomes fixed. The contents of this final list is
307 -- only partially specified: it will contain at least all the items of
308 -- the stream that were evaluated prior to the handle becoming closed.
310 -- Any I\/O errors encountered while a handle is semi-closed are simply
313 -- This operation may fail with:
315 -- * 'isEOFError' if the end of file has been reached.
317 hGetContents :: Handle -> IO String
318 hGetContents handle =
319 withHandle "hGetContents" handle $ \handle_ ->
320 case haType handle_ of
321 ClosedHandle -> ioe_closedHandle
322 SemiClosedHandle -> ioe_closedHandle
323 AppendHandle -> ioe_notReadable
324 WriteHandle -> ioe_notReadable
325 _ -> do xs <- lazyRead handle
326 return (handle_{ haType=SemiClosedHandle}, xs )
328 -- Note that someone may close the semi-closed handle (or change its
329 -- buffering), so each time these lazy read functions are pulled on,
330 -- they have to check whether the handle has indeed been closed.
332 lazyRead :: Handle -> IO String
335 withHandle "lazyRead" handle $ \ handle_ -> do
336 case haType handle_ of
337 ClosedHandle -> return (handle_, "")
338 SemiClosedHandle -> lazyRead' handle handle_
340 (IOError (Just handle) IllegalOperation "lazyRead"
341 "illegal handle type" Nothing)
343 lazyRead' h handle_ = do
344 let ref = haBuffer handle_
347 -- even a NoBuffering handle can have a char in the buffer...
350 if not (bufferEmpty buf)
351 then lazyReadHaveBuffer h handle_ fd ref buf
354 case haBufferMode handle_ of
356 -- make use of the minimal buffer we already have
358 r <- readRawBuffer "lazyRead" fd (haIsStream handle_) raw 0 1
360 then do (handle_,_) <- hClose_help handle_
362 else do (c,_) <- readCharFromBuffer raw 0
364 return (handle_, c : rest)
366 LineBuffering -> lazyReadBuffered h handle_ fd ref buf
367 BlockBuffering _ -> lazyReadBuffered h handle_ fd ref buf
369 -- we never want to block during the read, so we call fillReadBuffer with
370 -- is_line==True, which tells it to "just read what there is".
371 lazyReadBuffered h handle_ fd ref buf = do
373 (do buf <- fillReadBuffer fd True{-is_line-} (haIsStream handle_) buf
374 lazyReadHaveBuffer h handle_ fd ref buf
376 -- all I/O errors are discarded. Additionally, we close the handle.
377 (\e -> do (handle_,_) <- hClose_help handle_
381 lazyReadHaveBuffer h handle_ fd ref buf = do
383 writeIORef ref buf{ bufRPtr=0, bufWPtr=0 }
384 s <- unpackAcc (bufBuf buf) (bufRPtr buf) (bufWPtr buf) more
388 unpackAcc :: RawBuffer -> Int -> Int -> [Char] -> IO [Char]
389 unpackAcc buf r 0 acc = return acc
390 unpackAcc buf (I# r) (I# len) acc = IO $ \s -> unpack acc (len -# 1#) s
393 | i <# r = (# s, acc #)
395 case readCharArray# buf i s of
396 (# s, ch #) -> unpack (C# ch : acc) (i -# 1#) s
398 -- ---------------------------------------------------------------------------
401 -- | Computation 'hPutChar' @hdl ch@ writes the character @ch@ to the
402 -- file or channel managed by @hdl@. Characters may be buffered if
403 -- buffering is enabled for @hdl@.
405 -- This operation may fail with:
407 -- * 'isFullError' if the device is full; or
409 -- * 'isPermissionError' if another system resource limit would be exceeded.
411 hPutChar :: Handle -> Char -> IO ()
412 hPutChar handle c = do
414 wantWritableHandle "hPutChar" handle $ \ handle_ -> do
415 let fd = haFD handle_
416 case haBufferMode handle_ of
417 LineBuffering -> hPutcBuffered handle_ True c
418 BlockBuffering _ -> hPutcBuffered handle_ False c
420 with (castCharToCChar c) $ \buf -> do
421 writeRawBufferPtr "hPutChar" fd (haIsStream handle_) buf 0 1
424 hPutcBuffered handle_ is_line c = do
425 let ref = haBuffer handle_
428 w' <- writeCharIntoBuffer (bufBuf buf) w c
429 let new_buf = buf{ bufWPtr = w' }
430 if bufferFull new_buf || is_line && c == '\n'
432 flushed_buf <- flushWriteBuffer (haFD handle_) (haIsStream handle_) new_buf
433 writeIORef ref flushed_buf
435 writeIORef ref new_buf
438 hPutChars :: Handle -> [Char] -> IO ()
439 hPutChars handle [] = return ()
440 hPutChars handle (c:cs) = hPutChar handle c >> hPutChars handle cs
442 -- ---------------------------------------------------------------------------
445 -- We go to some trouble to avoid keeping the handle locked while we're
446 -- evaluating the string argument to hPutStr, in case doing so triggers another
447 -- I/O operation on the same handle which would lead to deadlock. The classic
450 -- putStr (trace "hello" "world")
452 -- so the basic scheme is this:
454 -- * copy the string into a fresh buffer,
455 -- * "commit" the buffer to the handle.
457 -- Committing may involve simply copying the contents of the new
458 -- buffer into the handle's buffer, flushing one or both buffers, or
459 -- maybe just swapping the buffers over (if the handle's buffer was
460 -- empty). See commitBuffer below.
462 -- | Computation 'hPutStr' @hdl s@ writes the string
463 -- @s@ to the file or channel managed by @hdl@.
465 -- This operation may fail with:
467 -- * 'isFullError' if the device is full; or
469 -- * 'isPermissionError' if another system resource limit would be exceeded.
471 hPutStr :: Handle -> String -> IO ()
472 hPutStr handle str = do
473 buffer_mode <- wantWritableHandle "hPutStr" handle
474 (\ handle_ -> do getSpareBuffer handle_)
476 (NoBuffering, _) -> do
477 hPutChars handle str -- v. slow, but we don't care
478 (LineBuffering, buf) -> do
479 writeLines handle buf str
480 (BlockBuffering _, buf) -> do
481 writeBlocks handle buf str
484 getSpareBuffer :: Handle__ -> IO (BufferMode, Buffer)
485 getSpareBuffer Handle__{haBuffer=ref,
490 NoBuffering -> return (mode, error "no buffer!")
492 bufs <- readIORef spare_ref
495 BufferListCons b rest -> do
496 writeIORef spare_ref rest
497 return ( mode, newEmptyBuffer b WriteBuffer (bufSize buf))
499 new_buf <- allocateBuffer (bufSize buf) WriteBuffer
500 return (mode, new_buf)
503 writeLines :: Handle -> Buffer -> String -> IO ()
504 writeLines hdl Buffer{ bufBuf=raw, bufSize=len } s =
506 shoveString :: Int -> [Char] -> IO ()
507 -- check n == len first, to ensure that shoveString is strict in n.
508 shoveString n cs | n == len = do
509 new_buf <- commitBuffer hdl raw len n True{-needs flush-} False
510 writeLines hdl new_buf cs
511 shoveString n [] = do
512 commitBuffer hdl raw len n False{-no flush-} True{-release-}
514 shoveString n (c:cs) = do
515 n' <- writeCharIntoBuffer raw n c
518 new_buf <- commitBuffer hdl raw len n' True{-needs flush-} False
519 writeLines hdl new_buf cs
525 writeBlocks :: Handle -> Buffer -> String -> IO ()
526 writeBlocks hdl Buffer{ bufBuf=raw, bufSize=len } s =
528 shoveString :: Int -> [Char] -> IO ()
529 -- check n == len first, to ensure that shoveString is strict in n.
530 shoveString n cs | n == len = do
531 new_buf <- commitBuffer hdl raw len n True{-needs flush-} False
532 writeBlocks hdl new_buf cs
533 shoveString n [] = do
534 commitBuffer hdl raw len n False{-no flush-} True{-release-}
536 shoveString n (c:cs) = do
537 n' <- writeCharIntoBuffer raw n c
542 -- -----------------------------------------------------------------------------
543 -- commitBuffer handle buf sz count flush release
545 -- Write the contents of the buffer 'buf' ('sz' bytes long, containing
546 -- 'count' bytes of data) to handle (handle must be block or line buffered).
550 -- for block/line buffering,
551 -- 1. If there isn't room in the handle buffer, flush the handle
554 -- 2. If the handle buffer is empty,
556 -- then write buf directly to the device.
557 -- else swap the handle buffer with buf.
559 -- 3. If the handle buffer is non-empty, copy buf into the
560 -- handle buffer. Then, if flush != 0, flush
564 :: Handle -- handle to commit to
565 -> RawBuffer -> Int -- address and size (in bytes) of buffer
566 -> Int -- number of bytes of data in buffer
567 -> Bool -- True <=> flush the handle afterward
568 -> Bool -- release the buffer?
571 commitBuffer hdl raw sz@(I# _) count@(I# _) flush release = do
572 wantWritableHandle "commitAndReleaseBuffer" hdl $
573 commitBuffer' raw sz count flush release
575 -- Explicitly lambda-lift this function to subvert GHC's full laziness
576 -- optimisations, which otherwise tends to float out subexpressions
577 -- past the \handle, which is really a pessimisation in this case because
578 -- that lambda is a one-shot lambda.
580 -- Don't forget to export the function, to stop it being inlined too
581 -- (this appears to be better than NOINLINE, because the strictness
582 -- analyser still gets to worker-wrapper it).
584 -- This hack is a fairly big win for hPutStr performance. --SDM 18/9/2001
586 commitBuffer' raw sz@(I# _) count@(I# _) flush release
587 handle_@Handle__{ haFD=fd, haBuffer=ref, haBuffers=spare_buf_ref } = do
590 puts ("commitBuffer: sz=" ++ show sz ++ ", count=" ++ show count
591 ++ ", flush=" ++ show flush ++ ", release=" ++ show release ++"\n")
594 old_buf@Buffer{ bufBuf=old_raw, bufRPtr=r, bufWPtr=w, bufSize=size }
598 -- enough room in handle buffer?
599 if (not flush && (size - w > count))
600 -- The > is to be sure that we never exactly fill
601 -- up the buffer, which would require a flush. So
602 -- if copying the new data into the buffer would
603 -- make the buffer full, we just flush the existing
604 -- buffer and the new data immediately, rather than
605 -- copying before flushing.
607 -- not flushing, and there's enough room in the buffer:
608 -- just copy the data in and update bufWPtr.
609 then do memcpy_baoff_ba old_raw (fromIntegral w) raw (fromIntegral count)
610 writeIORef ref old_buf{ bufWPtr = w + count }
611 return (newEmptyBuffer raw WriteBuffer sz)
613 -- else, we have to flush
614 else do flushed_buf <- flushWriteBuffer fd (haIsStream handle_) old_buf
617 Buffer{ bufBuf=raw, bufState=WriteBuffer,
618 bufRPtr=0, bufWPtr=count, bufSize=sz }
620 -- if: (a) we don't have to flush, and
621 -- (b) size(new buffer) == size(old buffer), and
622 -- (c) new buffer is not full,
623 -- we can just just swap them over...
624 if (not flush && sz == size && count /= sz)
626 writeIORef ref this_buf
629 -- otherwise, we have to flush the new data too,
630 -- and start with a fresh buffer
632 flushWriteBuffer fd (haIsStream handle_) this_buf
633 writeIORef ref flushed_buf
634 -- if the sizes were different, then allocate
635 -- a new buffer of the correct size.
637 then return (newEmptyBuffer raw WriteBuffer sz)
638 else allocateBuffer size WriteBuffer
640 -- release the buffer if necessary
642 Buffer{ bufSize=buf_ret_sz, bufBuf=buf_ret_raw } -> do
643 if release && buf_ret_sz == size
645 spare_bufs <- readIORef spare_buf_ref
646 writeIORef spare_buf_ref
647 (BufferListCons buf_ret_raw spare_bufs)
652 -- ---------------------------------------------------------------------------
653 -- Reading/writing sequences of bytes.
655 -- ---------------------------------------------------------------------------
658 -- | 'hPutBuf' @hdl buf count@ writes @count@ 8-bit bytes from the
659 -- buffer @buf@ to the handle @hdl@. It returns ().
661 -- This operation may fail with:
663 -- * 'ResourceVanished' if the handle is a pipe or socket, and the
664 -- reading end is closed. (If this is a POSIX system, and the program
665 -- has not asked to ignore SIGPIPE, then a SIGPIPE may be delivered
666 -- instead, whose default action is to terminate the program).
668 hPutBuf :: Handle -- handle to write to
669 -> Ptr a -- address of buffer
670 -> Int -- number of bytes of data in buffer
672 hPutBuf h ptr count = do hPutBuf' h ptr count True; return ()
675 :: Handle -- handle to write to
676 -> Ptr a -- address of buffer
677 -> Int -- number of bytes of data in buffer
678 -> IO Int -- returns: number of bytes written
679 hPutBufNonBlocking h ptr count = hPutBuf' h ptr count False
681 hPutBuf':: Handle -- handle to write to
682 -> Ptr a -- address of buffer
683 -> Int -- number of bytes of data in buffer
684 -> Bool -- allow blocking?
686 hPutBuf' handle ptr count can_block
687 | count == 0 = return 0
688 | count < 0 = illegalBufferSize handle "hPutBuf" count
690 wantWritableHandle "hPutBuf" handle $
691 \ handle_@Handle__{ haFD=fd, haBuffer=ref, haIsStream=is_stream } ->
692 bufWrite fd ref is_stream ptr count can_block
694 bufWrite fd ref is_stream ptr count can_block =
695 seq count $ seq fd $ do -- strictness hack
696 old_buf@Buffer{ bufBuf=old_raw, bufRPtr=r, bufWPtr=w, bufSize=size }
699 -- enough room in handle buffer?
700 if (size - w > count)
701 -- There's enough room in the buffer:
702 -- just copy the data in and update bufWPtr.
703 then do memcpy_baoff_ptr old_raw (fromIntegral w) ptr (fromIntegral count)
704 writeIORef ref old_buf{ bufWPtr = w + count }
707 -- else, we have to flush
708 else do flushed_buf <- flushWriteBuffer fd is_stream old_buf
709 -- TODO: we should do a non-blocking flush here
710 writeIORef ref flushed_buf
711 -- if we can fit in the buffer, then just loop
713 then bufWrite fd ref is_stream ptr count can_block
715 then do writeChunk fd is_stream (castPtr ptr) count
717 else writeChunkNonBlocking fd is_stream ptr count
719 writeChunk :: FD -> Bool -> Ptr CChar -> Int -> IO ()
720 writeChunk fd is_stream ptr bytes = loop 0 bytes
722 loop :: Int -> Int -> IO ()
723 loop _ bytes | bytes <= 0 = return ()
725 r <- fromIntegral `liftM`
726 writeRawBufferPtr "writeChunk" fd is_stream ptr
727 off (fromIntegral bytes)
728 -- write can't return 0
729 loop (off + r) (bytes - r)
731 writeChunkNonBlocking :: FD -> Bool -> Ptr a -> Int -> IO Int
732 writeChunkNonBlocking fd is_stream ptr bytes = loop 0 bytes
734 loop :: Int -> Int -> IO Int
735 loop off bytes | bytes <= 0 = return off
737 #ifndef mingw32_HOST_OS
738 ssize <- c_write fd (ptr `plusPtr` off) (fromIntegral bytes)
739 let r = fromIntegral ssize :: Int
741 then do errno <- getErrno
742 if (errno == eAGAIN || errno == eWOULDBLOCK)
744 else throwErrno "writeChunk"
745 else loop (off + r) (bytes - r)
747 (ssize, rc) <- asyncWrite (fromIntegral fd)
748 (fromIntegral $ fromEnum is_stream)
751 let r = fromIntegral ssize :: Int
753 then ioError (errnoToIOError "hPutBufNonBlocking" (Errno (fromIntegral rc)) Nothing Nothing)
754 else loop (off + r) (bytes - r)
757 -- ---------------------------------------------------------------------------
760 -- | 'hGetBuf' @hdl buf count@ reads data from the handle @hdl@
761 -- into the buffer @buf@ until either EOF is reached or
762 -- @count@ 8-bit bytes have been read.
763 -- It returns the number of bytes actually read. This may be zero if
764 -- EOF was reached before any data was read (or if @count@ is zero).
766 -- 'hGetBuf' never raises an EOF exception, instead it returns a value
767 -- smaller than @count@.
769 -- If the handle is a pipe or socket, and the writing end
770 -- is closed, 'hGetBuf' will behave as if EOF was reached.
772 hGetBuf :: Handle -> Ptr a -> Int -> IO Int
774 | count == 0 = return 0
775 | count < 0 = illegalBufferSize h "hGetBuf" count
777 wantReadableHandle "hGetBuf" h $
778 \ handle_@Handle__{ haFD=fd, haBuffer=ref, haIsStream=is_stream } -> do
779 bufRead fd ref is_stream ptr 0 count
781 -- small reads go through the buffer, large reads are satisfied by
782 -- taking data first from the buffer and then direct from the file
784 bufRead fd ref is_stream ptr so_far count =
785 seq fd $ seq so_far $ seq count $ do -- strictness hack
786 buf@Buffer{ bufBuf=raw, bufWPtr=w, bufRPtr=r, bufSize=sz } <- readIORef ref
788 then if count > sz -- small read?
789 then do rest <- readChunk fd is_stream ptr count
790 return (so_far + rest)
791 else do mb_buf <- maybeFillReadBuffer fd True is_stream buf
793 Nothing -> return so_far -- got nothing, we're done
796 bufRead fd ref is_stream ptr so_far count
801 memcpy_ptr_baoff ptr raw (fromIntegral r) (fromIntegral count)
802 writeIORef ref buf{ bufWPtr=0, bufRPtr=0 }
803 return (so_far + count)
807 memcpy_ptr_baoff ptr raw (fromIntegral r) (fromIntegral count)
808 writeIORef ref buf{ bufRPtr = r + count }
809 return (so_far + count)
812 memcpy_ptr_baoff ptr raw (fromIntegral r) (fromIntegral avail)
813 writeIORef ref buf{ bufWPtr=0, bufRPtr=0 }
814 let remaining = count - avail
815 so_far' = so_far + avail
816 ptr' = ptr `plusPtr` avail
819 then bufRead fd ref is_stream ptr' so_far' remaining
822 rest <- readChunk fd is_stream ptr' remaining
823 return (so_far' + rest)
825 readChunk :: FD -> Bool -> Ptr a -> Int -> IO Int
826 readChunk fd is_stream ptr bytes = loop 0 bytes
828 loop :: Int -> Int -> IO Int
829 loop off bytes | bytes <= 0 = return off
831 r <- fromIntegral `liftM`
832 readRawBufferPtr "readChunk" fd is_stream
833 (castPtr ptr) off (fromIntegral bytes)
836 else loop (off + r) (bytes - r)
839 -- | 'hGetBufNonBlocking' @hdl buf count@ reads data from the handle @hdl@
840 -- into the buffer @buf@ until either EOF is reached, or
841 -- @count@ 8-bit bytes have been read, or there is no more data available
842 -- to read immediately.
844 -- 'hGetBufNonBlocking' is identical to 'hGetBuf', except that it will
845 -- never block waiting for data to become available, instead it returns
846 -- only whatever data is available. To wait for data to arrive before
847 -- calling 'hGetBufNonBlocking', use 'hWaitForInput'.
849 -- If the handle is a pipe or socket, and the writing end
850 -- is closed, 'hGetBufNonBlocking' will behave as if EOF was reached.
852 hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
853 hGetBufNonBlocking h ptr count
854 | count == 0 = return 0
855 | count < 0 = illegalBufferSize h "hGetBufNonBlocking" count
857 wantReadableHandle "hGetBufNonBlocking" h $
858 \ handle_@Handle__{ haFD=fd, haBuffer=ref, haIsStream=is_stream } -> do
859 bufReadNonBlocking fd ref is_stream ptr 0 count
861 bufReadNonBlocking fd ref is_stream ptr so_far count =
862 seq fd $ seq so_far $ seq count $ do -- strictness hack
863 buf@Buffer{ bufBuf=raw, bufWPtr=w, bufRPtr=r, bufSize=sz } <- readIORef ref
865 then if count > sz -- large read?
866 then do rest <- readChunkNonBlocking fd is_stream ptr count
867 return (so_far + rest)
868 else do buf' <- fillReadBufferWithoutBlocking fd is_stream buf
869 case buf' of { Buffer{ bufWPtr=w } ->
872 else do writeIORef ref buf'
873 bufReadNonBlocking fd ref is_stream ptr
875 -- NOTE: new count is 'min count w'
876 -- so we will just copy the contents of the
877 -- buffer in the recursive call, and not
884 memcpy_ptr_baoff ptr raw (fromIntegral r) (fromIntegral count)
885 writeIORef ref buf{ bufWPtr=0, bufRPtr=0 }
886 return (so_far + count)
890 memcpy_ptr_baoff ptr raw (fromIntegral r) (fromIntegral count)
891 writeIORef ref buf{ bufRPtr = r + count }
892 return (so_far + count)
895 memcpy_ptr_baoff ptr raw (fromIntegral r) (fromIntegral avail)
896 writeIORef ref buf{ bufWPtr=0, bufRPtr=0 }
897 let remaining = count - avail
898 so_far' = so_far + avail
899 ptr' = ptr `plusPtr` avail
901 -- we haven't attempted to read anything yet if we get to here.
903 then bufReadNonBlocking fd ref is_stream ptr' so_far' remaining
906 rest <- readChunkNonBlocking fd is_stream ptr' remaining
907 return (so_far' + rest)
910 readChunkNonBlocking :: FD -> Bool -> Ptr a -> Int -> IO Int
911 readChunkNonBlocking fd is_stream ptr bytes = do
913 readRawBufferPtrNoBlock "readChunkNonBlocking" fd is_stream
914 (castPtr ptr) 0 (fromIntegral bytes)
916 -- we don't have non-blocking read support on Windows, so just invoke
917 -- the ordinary low-level read which will block until data is available,
918 -- but won't wait for the whole buffer to fill.
920 slurpFile :: FilePath -> IO (Ptr (), Int)
922 handle <- openFile fname ReadMode
923 sz <- hFileSize handle
924 if sz > fromIntegral (maxBound::Int) then
925 ioError (userError "slurpFile: file too big")
927 let sz_i = fromIntegral sz
928 if sz_i == 0 then return (nullPtr, 0) else do
929 chunk <- mallocBytes sz_i
930 r <- hGetBuf handle chunk sz_i
934 -- ---------------------------------------------------------------------------
937 foreign import ccall unsafe "__hscore_memcpy_src_off"
938 memcpy_ba_baoff :: RawBuffer -> RawBuffer -> CInt -> CSize -> IO (Ptr ())
939 foreign import ccall unsafe "__hscore_memcpy_src_off"
940 memcpy_ptr_baoff :: Ptr a -> RawBuffer -> CInt -> CSize -> IO (Ptr ())
941 foreign import ccall unsafe "__hscore_memcpy_dst_off"
942 memcpy_baoff_ba :: RawBuffer -> CInt -> RawBuffer -> CSize -> IO (Ptr ())
943 foreign import ccall unsafe "__hscore_memcpy_dst_off"
944 memcpy_baoff_ptr :: RawBuffer -> CInt -> Ptr a -> CSize -> IO (Ptr ())
946 -----------------------------------------------------------------------------
949 illegalBufferSize :: Handle -> String -> Int -> IO a
950 illegalBufferSize handle fn sz =
951 ioException (IOError (Just handle)
953 ("illegal buffer size " ++ showsPrec 9 sz [])