1 {-# OPTIONS_GHC -XNoImplicitPrelude -#include "HsBase.h" #-}
2 {-# OPTIONS_GHC -XRecordWildCards -XBangPatterns #-}
3 {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
4 {-# OPTIONS_GHC -fno-warn-unused-matches #-}
5 {-# OPTIONS_HADDOCK hide #-}
7 -----------------------------------------------------------------------------
9 -- Module : GHC.IO.Text
10 -- Copyright : (c) The University of Glasgow, 1992-2008
11 -- License : see libraries/base/LICENSE
13 -- Maintainer : libraries@haskell.org
14 -- Stability : internal
15 -- Portability : non-portable
17 -- String I\/O functions
19 -----------------------------------------------------------------------------
22 module GHC.IO.Handle.Text (
23 hWaitForInput, hGetChar, hGetLine, hGetContents, hPutChar, hPutStr,
24 commitBuffer', -- hack, see below
25 hGetBuf, hGetBufNonBlocking, hPutBuf, hPutBufNonBlocking,
32 import qualified GHC.IO.BufferedIO as Buffered
33 import GHC.IO.Exception
35 import GHC.IO.Handle.Types
36 import GHC.IO.Handle.Internals
37 import qualified GHC.IO.Device as IODevice
38 import qualified GHC.IO.Device as RawIO
44 import System.IO.Error
55 -- ---------------------------------------------------------------------------
56 -- Simple input operations
58 -- If hWaitForInput finds anything in the Handle's buffer, it
59 -- immediately returns. If not, it tries to read from the underlying
60 -- OS handle. Notice that for buffered Handles connected to terminals
61 -- this means waiting until a complete line is available.
63 -- | Computation 'hWaitForInput' @hdl t@
64 -- waits until input is available on handle @hdl@.
65 -- It returns 'True' as soon as input is available on @hdl@,
66 -- or 'False' if no input is available within @t@ milliseconds.
68 -- If @t@ is less than zero, then @hWaitForInput@ waits indefinitely.
70 -- This operation may fail with:
72 -- * 'isEOFError' if the end of file has been reached.
74 -- NOTE for GHC users: unless you use the @-threaded@ flag,
75 -- @hWaitForInput t@ where @t >= 0@ will block all other Haskell
76 -- threads for the duration of the call. It behaves like a
77 -- @safe@ foreign call in this respect.
79 hWaitForInput :: Handle -> Int -> IO Bool
80 hWaitForInput h msecs = do
81 wantReadableHandle_ "hWaitForInput" h $ \ handle_@Handle__{..} -> do
82 cbuf <- readIORef haCharBuffer
84 if not (isEmptyBuffer cbuf) then return True else do
87 then do cbuf' <- readTextDevice handle_ cbuf
88 writeIORef haCharBuffer cbuf'
91 -- there might be bytes in the byte buffer waiting to be decoded
92 cbuf' <- readTextDeviceNonBlocking handle_ cbuf
93 writeIORef haCharBuffer cbuf'
95 if not (isEmptyBuffer cbuf') then return True else do
97 r <- IODevice.ready haDevice False{-read-} msecs
98 if r then do -- Call hLookAhead' to throw an EOF
99 -- exception if appropriate
100 _ <- hLookAhead_ handle_
103 -- XXX we should only return when there are full characters
104 -- not when there are only bytes. That would mean looping
105 -- and re-running IODevice.ready if we don't have any full
106 -- characters; but we don't know how long we've waited
109 -- ---------------------------------------------------------------------------
112 -- | Computation 'hGetChar' @hdl@ reads a character from the file or
113 -- channel managed by @hdl@, blocking until a character is available.
115 -- This operation may fail with:
117 -- * 'isEOFError' if the end of file has been reached.
119 hGetChar :: Handle -> IO Char
121 wantReadableHandle_ "hGetChar" handle $ \handle_@Handle__{..} -> do
123 -- buffering mode makes no difference: we just read whatever is available
124 -- from the device (blocking only if there is nothing available), and then
125 -- return the first character.
126 -- See [note Buffered Reading] in GHC.IO.Handle.Types
127 buf0 <- readIORef haCharBuffer
129 buf1 <- if isEmptyBuffer buf0
130 then readTextDevice handle_ buf0
133 (c1,i) <- readCharBuf (bufRaw buf1) (bufL buf1)
134 let buf2 = bufferAdjustL i buf1
136 if haInputNL == CRLF && c1 == '\r'
138 mbuf3 <- if isEmptyBuffer buf2
139 then maybeFillReadBuffer handle_ buf2
140 else return (Just buf2)
143 -- EOF, so just return the '\r' we have
145 writeIORef haCharBuffer buf2
148 (c2,i2) <- readCharBuf (bufRaw buf2) (bufL buf2)
151 writeIORef haCharBuffer (bufferAdjustL i2 buf3)
154 -- not a \r\n sequence, so just return the \r
155 writeIORef haCharBuffer buf3
158 writeIORef haCharBuffer buf2
161 -- ---------------------------------------------------------------------------
164 -- | Computation 'hGetLine' @hdl@ reads a line from the file or
165 -- channel managed by @hdl@.
167 -- This operation may fail with:
169 -- * 'isEOFError' if the end of file is encountered when reading
170 -- the /first/ character of the line.
172 -- If 'hGetLine' encounters end-of-file at any other point while reading
173 -- in a line, it is treated as a line terminator and the (partial)
176 hGetLine :: Handle -> IO String
178 wantReadableHandle_ "hGetLine" h $ \ handle_ -> do
179 hGetLineBuffered handle_
181 hGetLineBuffered :: Handle__ -> IO String
182 hGetLineBuffered handle_@Handle__{..} = do
183 buf <- readIORef haCharBuffer
184 hGetLineBufferedLoop handle_ buf []
186 hGetLineBufferedLoop :: Handle__
187 -> CharBuffer -> [String]
189 hGetLineBufferedLoop handle_@Handle__{..}
190 buf@Buffer{ bufL=r0, bufR=w, bufRaw=raw0 } xss =
192 -- find the end-of-line character, if there is one
194 | r == w = return (False, w)
196 (c,r') <- readCharBuf raw r
198 then return (True, r) -- NB. not r': don't include the '\n'
201 (eol, off) <- loop raw0 r0
203 debugIO ("hGetLineBufferedLoop: r=" ++ show r0 ++ ", w=" ++ show w ++ ", off=" ++ show off)
205 (xs,r') <- if haInputNL == CRLF
206 then unpack_nl raw0 r0 off ""
207 else do xs <- unpack raw0 r0 off ""
210 -- if eol == True, then off is the offset of the '\n'
211 -- otherwise off == w and the buffer is now empty.
213 then do writeIORef haCharBuffer (bufferAdjustL (off+1) buf)
214 return (concat (reverse (xs:xss)))
216 let buf1 = bufferAdjustL r' buf
217 maybe_buf <- maybeFillReadBuffer handle_ buf1
219 -- Nothing indicates we caught an EOF, and we may have a
220 -- partial line to return.
222 -- we reached EOF. There might be a lone \r left
223 -- in the buffer, so check for that and
224 -- append it to the line if necessary.
226 let pre = if not (isEmptyBuffer buf1) then "\r" else ""
227 writeIORef haCharBuffer buf1{ bufL=0, bufR=0 }
228 let str = concat (reverse (pre:xs:xss))
233 hGetLineBufferedLoop handle_ new_buf (xs:xss)
235 maybeFillReadBuffer :: Handle__ -> CharBuffer -> IO (Maybe CharBuffer)
236 maybeFillReadBuffer handle_ buf
238 (do buf' <- getSomeCharacters handle_ buf
241 (\e -> do if isEOFError e
246 #define CHARBUF_UTF32
247 -- #define CHARBUF_UTF16
249 -- NB. performance-critical code: eyeball the Core.
250 unpack :: RawCharBuffer -> Int -> Int -> [Char] -> IO [Char]
251 unpack !buf !r !w acc0
252 | r == w = return acc0
254 withRawBuffer buf $ \pbuf ->
260 -- reverse-order decoding of UTF-16
261 c2 <- peekElemOff pbuf i
262 if (c2 < 0xdc00 || c2 > 0xdffff)
263 then unpackRB (unsafeChr (fromIntegral c2) : acc) (i-1)
264 else do c1 <- peekElemOff pbuf (i-1)
265 let c = (fromIntegral c1 - 0xd800) * 0x400 +
266 (fromIntegral c2 - 0xdc00) + 0x10000
267 unpackRB (unsafeChr c : acc) (i-2)
269 c <- peekElemOff pbuf i
270 unpackRB (c:acc) (i-1)
275 -- NB. performance-critical code: eyeball the Core.
276 unpack_nl :: RawCharBuffer -> Int -> Int -> [Char] -> IO ([Char],Int)
277 unpack_nl !buf !r !w acc0
278 | r == w = return (acc0, 0)
280 withRawBuffer buf $ \pbuf ->
285 c <- peekElemOff pbuf i
286 if (c == '\n' && i > r)
288 c1 <- peekElemOff pbuf (i-1)
290 then unpackRB ('\n':acc) (i-2)
291 else unpackRB ('\n':acc) (i-1)
293 unpackRB (c:acc) (i-1)
295 c <- peekElemOff pbuf (w-1)
298 -- If the last char is a '\r', we need to know whether or
299 -- not it is followed by a '\n', so leave it in the buffer
300 -- for now and just unpack the rest.
301 str <- unpackRB acc0 (w-2)
304 str <- unpackRB acc0 (w-1)
308 -- -----------------------------------------------------------------------------
311 -- hGetContents on a DuplexHandle only affects the read side: you can
312 -- carry on writing to it afterwards.
314 -- | Computation 'hGetContents' @hdl@ returns the list of characters
315 -- corresponding to the unread portion of the channel or file managed
316 -- by @hdl@, which is put into an intermediate state, /semi-closed/.
317 -- In this state, @hdl@ is effectively closed,
318 -- but items are read from @hdl@ on demand and accumulated in a special
319 -- list returned by 'hGetContents' @hdl@.
321 -- Any operation that fails because a handle is closed,
322 -- also fails if a handle is semi-closed. The only exception is 'hClose'.
323 -- A semi-closed handle becomes closed:
325 -- * if 'hClose' is applied to it;
327 -- * if an I\/O error occurs when reading an item from the handle;
329 -- * or once the entire contents of the handle has been read.
331 -- Once a semi-closed handle becomes closed, the contents of the
332 -- associated list becomes fixed. The contents of this final list is
333 -- only partially specified: it will contain at least all the items of
334 -- the stream that were evaluated prior to the handle becoming closed.
336 -- Any I\/O errors encountered while a handle is semi-closed are simply
339 -- This operation may fail with:
341 -- * 'isEOFError' if the end of file has been reached.
343 hGetContents :: Handle -> IO String
344 hGetContents handle =
345 wantReadableHandle "hGetContents" handle $ \handle_ -> do
346 xs <- lazyRead handle
347 return (handle_{ haType=SemiClosedHandle}, xs )
349 -- Note that someone may close the semi-closed handle (or change its
350 -- buffering), so each time these lazy read functions are pulled on,
351 -- they have to check whether the handle has indeed been closed.
353 lazyRead :: Handle -> IO String
356 withHandle "hGetContents" handle $ \ handle_ -> do
357 case haType handle_ of
358 ClosedHandle -> return (handle_, "")
359 SemiClosedHandle -> lazyReadBuffered handle handle_
361 (IOError (Just handle) IllegalOperation "hGetContents"
362 "illegal handle type" Nothing Nothing)
364 lazyReadBuffered :: Handle -> Handle__ -> IO (Handle__, [Char])
365 lazyReadBuffered h handle_@Handle__{..} = do
366 buf <- readIORef haCharBuffer
369 buf'@Buffer{..} <- getSomeCharacters handle_ buf
370 lazy_rest <- lazyRead h
371 (s,r) <- if haInputNL == CRLF
372 then unpack_nl bufRaw bufL bufR lazy_rest
373 else do s <- unpack bufRaw bufL bufR lazy_rest
375 writeIORef haCharBuffer (bufferAdjustL r buf')
378 (\e -> do (handle_', _) <- hClose_help handle_
379 debugIO ("hGetContents caught: " ++ show e)
380 -- We might have a \r cached in CRLF mode. So we
381 -- need to check for that and return it:
382 let r = if isEOFError e
383 then if not (isEmptyBuffer buf)
387 throw (augmentIOError e "hGetContents" h)
392 -- ensure we have some characters in the buffer
393 getSomeCharacters :: Handle__ -> CharBuffer -> IO CharBuffer
394 getSomeCharacters handle_@Handle__{..} buf@Buffer{..} =
395 case bufferElems buf of
397 -- buffer empty: read some more
398 0 -> readTextDevice handle_ buf
400 -- if the buffer has a single '\r' in it and we're doing newline
401 -- translation: read some more
402 1 | haInputNL == CRLF -> do
403 (c,_) <- readCharBuf bufRaw bufL
405 then do -- shuffle the '\r' to the beginning. This is only safe
406 -- if we're about to call readTextDevice, otherwise it
407 -- would mess up flushCharBuffer.
408 -- See [note Buffer Flushing], GHC.IO.Handle.Types
409 _ <- writeCharBuf bufRaw 0 '\r'
410 let buf' = buf{ bufL=0, bufR=1 }
411 readTextDevice handle_ buf'
415 -- buffer has some chars in it already: just return it
419 -- ---------------------------------------------------------------------------
422 -- | Computation 'hPutChar' @hdl ch@ writes the character @ch@ to the
423 -- file or channel managed by @hdl@. Characters may be buffered if
424 -- buffering is enabled for @hdl@.
426 -- This operation may fail with:
428 -- * 'isFullError' if the device is full; or
430 -- * 'isPermissionError' if another system resource limit would be exceeded.
432 hPutChar :: Handle -> Char -> IO ()
433 hPutChar handle c = do
435 wantWritableHandle "hPutChar" handle $ \ handle_ -> do
436 case haBufferMode handle_ of
437 LineBuffering -> hPutcBuffered handle_ True c
438 _other -> hPutcBuffered handle_ False c
440 hPutcBuffered :: Handle__ -> Bool -> Char -> IO ()
441 hPutcBuffered handle_@Handle__{..} is_line c = do
442 buf <- readIORef haCharBuffer
444 then do buf1 <- if haOutputNL == CRLF
446 buf1 <- putc buf '\r'
452 flushed_buf <- flushWriteBuffer_ handle_ buf1
453 writeIORef haCharBuffer flushed_buf
455 writeIORef haCharBuffer buf1
458 writeIORef haCharBuffer buf1
460 putc buf@Buffer{ bufRaw=raw, bufR=w } c = do
461 debugIO ("putc: " ++ summaryBuffer buf)
462 w' <- writeCharBuf raw w c
463 let buf' = buf{ bufR = w' }
464 if isFullCharBuffer buf'
465 then flushWriteBuffer_ handle_ buf'
468 -- ---------------------------------------------------------------------------
471 -- We go to some trouble to avoid keeping the handle locked while we're
472 -- evaluating the string argument to hPutStr, in case doing so triggers another
473 -- I/O operation on the same handle which would lead to deadlock. The classic
476 -- putStr (trace "hello" "world")
478 -- so the basic scheme is this:
480 -- * copy the string into a fresh buffer,
481 -- * "commit" the buffer to the handle.
483 -- Committing may involve simply copying the contents of the new
484 -- buffer into the handle's buffer, flushing one or both buffers, or
485 -- maybe just swapping the buffers over (if the handle's buffer was
486 -- empty). See commitBuffer below.
488 -- | Computation 'hPutStr' @hdl s@ writes the string
489 -- @s@ to the file or channel managed by @hdl@.
491 -- This operation may fail with:
493 -- * 'isFullError' if the device is full; or
495 -- * 'isPermissionError' if another system resource limit would be exceeded.
497 hPutStr :: Handle -> String -> IO ()
498 hPutStr handle str = do
500 wantWritableHandle "hPutStr" handle $ \h_ -> do
501 bmode <- getSpareBuffer h_
502 return (bmode, haOutputNL h_)
505 (NoBuffering, _) -> do
506 hPutChars handle str -- v. slow, but we don't care
507 (LineBuffering, buf) -> do
508 writeBlocks handle True nl buf str
509 (BlockBuffering _, buf) -> do
510 writeBlocks handle False nl buf str
512 hPutChars :: Handle -> [Char] -> IO ()
513 hPutChars _ [] = return ()
514 hPutChars handle (c:cs) = hPutChar handle c >> hPutChars handle cs
516 getSpareBuffer :: Handle__ -> IO (BufferMode, CharBuffer)
517 getSpareBuffer Handle__{haCharBuffer=ref,
522 NoBuffering -> return (mode, error "no buffer!")
524 bufs <- readIORef spare_ref
527 BufferListCons b rest -> do
528 writeIORef spare_ref rest
529 return ( mode, emptyBuffer b (bufSize buf) WriteBuffer)
531 new_buf <- newCharBuffer (bufSize buf) WriteBuffer
532 return (mode, new_buf)
535 -- NB. performance-critical code: eyeball the Core.
536 writeBlocks :: Handle -> Bool -> Newline -> Buffer CharBufElem -> String -> IO ()
537 writeBlocks hdl line_buffered nl
538 buf@Buffer{ bufRaw=raw, bufSize=len } s =
540 shoveString :: Int -> [Char] -> IO ()
541 shoveString !n [] = do
542 _ <- commitBuffer hdl raw len n False{-no flush-} True{-release-}
544 shoveString !n (c:cs)
545 -- n+1 so we have enough room to write '\r\n' if necessary
547 new_buf <- commitBuffer hdl raw len n True{-needs flush-} False
548 writeBlocks hdl line_buffered nl new_buf (c:cs)
552 n1 <- writeCharBuf raw n '\r'
553 writeCharBuf raw n1 '\n'
558 new_buf <- commitBuffer hdl raw len n' True{-needs flush-} False
559 writeBlocks hdl line_buffered nl new_buf cs
563 n' <- writeCharBuf raw n c
568 -- -----------------------------------------------------------------------------
569 -- commitBuffer handle buf sz count flush release
571 -- Write the contents of the buffer 'buf' ('sz' bytes long, containing
572 -- 'count' bytes of data) to handle (handle must be block or line buffered).
576 -- for block/line buffering,
577 -- 1. If there isn't room in the handle buffer, flush the handle
580 -- 2. If the handle buffer is empty,
582 -- then write buf directly to the device.
583 -- else swap the handle buffer with buf.
585 -- 3. If the handle buffer is non-empty, copy buf into the
586 -- handle buffer. Then, if flush != 0, flush
590 :: Handle -- handle to commit to
591 -> RawCharBuffer -> Int -- address and size (in bytes) of buffer
592 -> Int -- number of bytes of data in buffer
593 -> Bool -- True <=> flush the handle afterward
594 -> Bool -- release the buffer?
597 commitBuffer hdl !raw !sz !count flush release =
598 wantWritableHandle "commitAndReleaseBuffer" hdl $
599 commitBuffer' raw sz count flush release
600 {-# NOINLINE commitBuffer #-}
602 -- Explicitly lambda-lift this function to subvert GHC's full laziness
603 -- optimisations, which otherwise tends to float out subexpressions
604 -- past the \handle, which is really a pessimisation in this case because
605 -- that lambda is a one-shot lambda.
607 -- Don't forget to export the function, to stop it being inlined too
608 -- (this appears to be better than NOINLINE, because the strictness
609 -- analyser still gets to worker-wrapper it).
611 -- This hack is a fairly big win for hPutStr performance. --SDM 18/9/2001
613 commitBuffer' :: RawCharBuffer -> Int -> Int -> Bool -> Bool -> Handle__
615 commitBuffer' raw sz@(I# _) count@(I# _) flush release
616 handle_@Handle__{ haCharBuffer=ref, haBuffers=spare_buf_ref } = do
618 debugIO ("commitBuffer: sz=" ++ show sz ++ ", count=" ++ show count
619 ++ ", flush=" ++ show flush ++ ", release=" ++ show release)
621 old_buf@Buffer{ bufRaw=old_raw, bufR=w, bufSize=size }
625 -- enough room in handle buffer?
626 if (not flush && (size - w > count))
627 -- The > is to be sure that we never exactly fill
628 -- up the buffer, which would require a flush. So
629 -- if copying the new data into the buffer would
630 -- make the buffer full, we just flush the existing
631 -- buffer and the new data immediately, rather than
632 -- copying before flushing.
634 -- not flushing, and there's enough room in the buffer:
635 -- just copy the data in and update bufR.
636 then do withRawBuffer raw $ \praw ->
637 copyToRawBuffer old_raw (w*charSize)
638 praw (fromIntegral (count*charSize))
639 writeIORef ref old_buf{ bufR = w + count }
640 return (emptyBuffer raw sz WriteBuffer)
642 -- else, we have to flush
643 else do flushed_buf <- flushWriteBuffer_ handle_ old_buf
646 Buffer{ bufRaw=raw, bufState=WriteBuffer,
647 bufL=0, bufR=count, bufSize=sz }
649 -- if: (a) we don't have to flush, and
650 -- (b) size(new buffer) == size(old buffer), and
651 -- (c) new buffer is not full,
652 -- we can just just swap them over...
653 if (not flush && sz == size && count /= sz)
655 writeIORef ref this_buf
658 -- otherwise, we have to flush the new data too,
659 -- and start with a fresh buffer
661 -- We're aren't going to use this buffer again
662 -- so we ignore the result of flushWriteBuffer_
663 _ <- flushWriteBuffer_ handle_ this_buf
664 writeIORef ref flushed_buf
665 -- if the sizes were different, then allocate
666 -- a new buffer of the correct size.
668 then return (emptyBuffer raw sz WriteBuffer)
669 else newCharBuffer size WriteBuffer
671 -- release the buffer if necessary
673 Buffer{ bufSize=buf_ret_sz, bufRaw=buf_ret_raw } -> do
674 if release && buf_ret_sz == size
676 spare_bufs <- readIORef spare_buf_ref
677 writeIORef spare_buf_ref
678 (BufferListCons buf_ret_raw spare_bufs)
683 -- ---------------------------------------------------------------------------
684 -- Reading/writing sequences of bytes.
686 -- ---------------------------------------------------------------------------
689 -- | 'hPutBuf' @hdl buf count@ writes @count@ 8-bit bytes from the
690 -- buffer @buf@ to the handle @hdl@. It returns ().
692 -- 'hPutBuf' ignores any text encoding that applies to the 'Handle',
693 -- writing the bytes directly to the underlying file or device.
695 -- 'hPutBuf' ignores the prevailing 'TextEncoding' and
696 -- 'NewlineMode' on the 'Handle', and writes bytes directly.
698 -- This operation may fail with:
700 -- * 'ResourceVanished' if the handle is a pipe or socket, and the
701 -- reading end is closed. (If this is a POSIX system, and the program
702 -- has not asked to ignore SIGPIPE, then a SIGPIPE may be delivered
703 -- instead, whose default action is to terminate the program).
705 hPutBuf :: Handle -- handle to write to
706 -> Ptr a -- address of buffer
707 -> Int -- number of bytes of data in buffer
709 hPutBuf h ptr count = do _ <- hPutBuf' h ptr count True
713 :: Handle -- handle to write to
714 -> Ptr a -- address of buffer
715 -> Int -- number of bytes of data in buffer
716 -> IO Int -- returns: number of bytes written
717 hPutBufNonBlocking h ptr count = hPutBuf' h ptr count False
719 hPutBuf':: Handle -- handle to write to
720 -> Ptr a -- address of buffer
721 -> Int -- number of bytes of data in buffer
722 -> Bool -- allow blocking?
724 hPutBuf' handle ptr count can_block
725 | count == 0 = return 0
726 | count < 0 = illegalBufferSize handle "hPutBuf" count
728 wantWritableHandle "hPutBuf" handle $
729 \ h_@Handle__{..} -> do
730 debugIO ("hPutBuf count=" ++ show count)
731 -- first flush the Char buffer if it is non-empty, then we
732 -- can work directly with the byte buffer
733 cbuf <- readIORef haCharBuffer
734 when (not (isEmptyBuffer cbuf)) $ flushWriteBuffer h_
736 r <- bufWrite h_ (castPtr ptr) count can_block
738 -- we must flush if this Handle is set to NoBuffering. If
739 -- it is set to LineBuffering, be conservative and flush
740 -- anyway (we didn't check for newlines in the data).
742 BlockBuffering _ -> do return ()
743 _line_or_no_buffering -> do flushWriteBuffer h_
746 bufWrite :: Handle__-> Ptr Word8 -> Int -> Bool -> IO Int
747 bufWrite h_@Handle__{..} ptr count can_block =
748 seq count $ do -- strictness hack
749 old_buf@Buffer{ bufRaw=old_raw, bufR=w, bufSize=size }
750 <- readIORef haByteBuffer
752 -- enough room in handle buffer?
753 if (size - w > count)
754 -- There's enough room in the buffer:
755 -- just copy the data in and update bufR.
756 then do debugIO ("hPutBuf: copying to buffer, w=" ++ show w)
757 copyToRawBuffer old_raw w ptr (fromIntegral count)
758 writeIORef haByteBuffer old_buf{ bufR = w + count }
761 -- else, we have to flush
762 else do debugIO "hPutBuf: flushing first"
763 old_buf' <- Buffered.flushWriteBuffer haDevice old_buf
764 -- TODO: we should do a non-blocking flush here
765 writeIORef haByteBuffer old_buf'
766 -- if we can fit in the buffer, then just loop
768 then bufWrite h_ ptr count can_block
770 then do writeChunk h_ (castPtr ptr) count
772 else writeChunkNonBlocking h_ (castPtr ptr) count
774 writeChunk :: Handle__ -> Ptr Word8 -> Int -> IO ()
775 writeChunk h_@Handle__{..} ptr bytes
776 | Just fd <- cast haDevice = RawIO.write (fd::FD) ptr bytes
777 | otherwise = error "Todo: hPutBuf"
779 writeChunkNonBlocking :: Handle__ -> Ptr Word8 -> Int -> IO Int
780 writeChunkNonBlocking h_@Handle__{..} ptr bytes
781 | Just fd <- cast haDevice = RawIO.writeNonBlocking (fd::FD) ptr bytes
782 | otherwise = error "Todo: hPutBuf"
784 -- ---------------------------------------------------------------------------
787 -- | 'hGetBuf' @hdl buf count@ reads data from the handle @hdl@
788 -- into the buffer @buf@ until either EOF is reached or
789 -- @count@ 8-bit bytes have been read.
790 -- It returns the number of bytes actually read. This may be zero if
791 -- EOF was reached before any data was read (or if @count@ is zero).
793 -- 'hGetBuf' ignores whatever 'TextEncoding' the 'Handle' is currently
794 -- using, and reads bytes directly from the underlying IO device.
796 -- 'hGetBuf' never raises an EOF exception, instead it returns a value
797 -- smaller than @count@.
799 -- If the handle is a pipe or socket, and the writing end
800 -- is closed, 'hGetBuf' will behave as if EOF was reached.
802 -- 'hGetBuf' ignores the prevailing 'TextEncoding' and 'NewlineMode'
803 -- on the 'Handle', and reads bytes directly.
805 hGetBuf :: Handle -> Ptr a -> Int -> IO Int
807 | count == 0 = return 0
808 | count < 0 = illegalBufferSize h "hGetBuf" count
810 wantReadableHandle_ "hGetBuf" h $ \ h_ -> do
811 flushCharReadBuffer h_
812 bufRead h_ (castPtr ptr) 0 count
814 -- small reads go through the buffer, large reads are satisfied by
815 -- taking data first from the buffer and then direct from the file
817 bufRead :: Handle__ -> Ptr Word8 -> Int -> Int -> IO Int
818 bufRead h_@Handle__{..} ptr so_far count =
819 seq so_far $ seq count $ do -- strictness hack
820 buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz } <- readIORef haByteBuffer
822 then if count > sz -- small read?
823 then do rest <- readChunk h_ ptr count
824 return (so_far + rest)
825 else do (r,buf') <- Buffered.fillReadBuffer haDevice buf
828 else do writeIORef haByteBuffer buf'
829 bufRead h_ ptr so_far count
834 copyFromRawBuffer ptr raw r count
835 writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
836 return (so_far + count)
840 copyFromRawBuffer ptr raw r count
841 writeIORef haByteBuffer buf{ bufL = r + count }
842 return (so_far + count)
845 copyFromRawBuffer ptr raw (fromIntegral r) (fromIntegral avail)
846 writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
847 let remaining = count - avail
848 so_far' = so_far + avail
849 ptr' = ptr `plusPtr` avail
852 then bufRead h_ ptr' so_far' remaining
855 rest <- readChunk h_ ptr' remaining
856 return (so_far' + rest)
858 readChunk :: Handle__ -> Ptr a -> Int -> IO Int
859 readChunk h_@Handle__{..} ptr bytes
860 | Just fd <- cast haDevice = loop fd 0 bytes
861 | otherwise = error "ToDo: hGetBuf"
863 loop :: FD -> Int -> Int -> IO Int
864 loop fd off bytes | bytes <= 0 = return off
865 loop fd off bytes = do
866 r <- RawIO.read (fd::FD) (ptr `plusPtr` off) (fromIntegral bytes)
869 else loop fd (off + r) (bytes - r)
871 -- | 'hGetBufNonBlocking' @hdl buf count@ reads data from the handle @hdl@
872 -- into the buffer @buf@ until either EOF is reached, or
873 -- @count@ 8-bit bytes have been read, or there is no more data available
874 -- to read immediately.
876 -- 'hGetBufNonBlocking' is identical to 'hGetBuf', except that it will
877 -- never block waiting for data to become available, instead it returns
878 -- only whatever data is available. To wait for data to arrive before
879 -- calling 'hGetBufNonBlocking', use 'hWaitForInput'.
881 -- 'hGetBufNonBlocking' ignores whatever 'TextEncoding' the 'Handle'
882 -- is currently using, and reads bytes directly from the underlying IO
885 -- If the handle is a pipe or socket, and the writing end
886 -- is closed, 'hGetBufNonBlocking' will behave as if EOF was reached.
888 -- 'hGetBufNonBlocking' ignores the prevailing 'TextEncoding' and
889 -- 'NewlineMode' on the 'Handle', and reads bytes directly.
891 hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
892 hGetBufNonBlocking h ptr count
893 | count == 0 = return 0
894 | count < 0 = illegalBufferSize h "hGetBufNonBlocking" count
896 wantReadableHandle_ "hGetBufNonBlocking" h $ \ h_ -> do
897 flushCharReadBuffer h_
898 bufReadNonBlocking h_ (castPtr ptr) 0 count
900 bufReadNonBlocking :: Handle__ -> Ptr Word8 -> Int -> Int -> IO Int
901 bufReadNonBlocking h_@Handle__{..} ptr so_far count =
902 seq so_far $ seq count $ do -- strictness hack
903 buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz } <- readIORef haByteBuffer
905 then if count > sz -- large read?
906 then do rest <- readChunkNonBlocking h_ ptr count
907 return (so_far + rest)
908 else do (r,buf') <- Buffered.fillReadBuffer0 haDevice buf
910 Nothing -> return so_far
911 Just 0 -> return so_far
913 writeIORef haByteBuffer buf'
914 bufReadNonBlocking h_ ptr so_far (min count r)
915 -- NOTE: new count is min count w'
916 -- so we will just copy the contents of the
917 -- buffer in the recursive call, and not
923 copyFromRawBuffer ptr raw r count
924 writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
925 return (so_far + count)
929 copyFromRawBuffer ptr raw r count
930 writeIORef haByteBuffer buf{ bufL = r + count }
931 return (so_far + count)
934 copyFromRawBuffer ptr raw (fromIntegral r) (fromIntegral avail)
935 writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
936 let remaining = count - avail
937 so_far' = so_far + avail
938 ptr' = ptr `plusPtr` avail
940 -- we haven't attempted to read anything yet if we get to here.
942 then bufReadNonBlocking h_ ptr' so_far' remaining
945 rest <- readChunkNonBlocking h_ ptr' remaining
946 return (so_far' + rest)
949 readChunkNonBlocking :: Handle__ -> Ptr Word8 -> Int -> IO Int
950 readChunkNonBlocking h_@Handle__{..} ptr bytes
951 | Just fd <- cast haDevice = do
952 m <- RawIO.readNonBlocking (fd::FD) ptr bytes
956 | otherwise = error "ToDo: hGetBuf"
958 -- ---------------------------------------------------------------------------
961 copyToRawBuffer :: RawBuffer e -> Int -> Ptr e -> Int -> IO ()
962 copyToRawBuffer raw off ptr bytes =
963 withRawBuffer raw $ \praw ->
964 do _ <- memcpy (praw `plusPtr` off) ptr (fromIntegral bytes)
967 copyFromRawBuffer :: Ptr e -> RawBuffer e -> Int -> Int -> IO ()
968 copyFromRawBuffer ptr raw off bytes =
969 withRawBuffer raw $ \praw ->
970 do _ <- memcpy ptr (praw `plusPtr` off) (fromIntegral bytes)
973 foreign import ccall unsafe "memcpy"
974 memcpy :: Ptr a -> Ptr a -> CSize -> IO (Ptr ())
976 -----------------------------------------------------------------------------
979 illegalBufferSize :: Handle -> String -> Int -> IO a
980 illegalBufferSize handle fn sz =
981 ioException (IOError (Just handle)
983 ("illegal buffer size " ++ showsPrec 9 sz [])