1 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
5 -- Module : GHC.IO.Handle.Types
6 -- Copyright : (c) The University of Glasgow, 1994-2009
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : libraries@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable
13 -- Basic types for the implementation of IO Handles.
15 -----------------------------------------------------------------------------
17 module GHC.IO.Handle.Types (
18 Handle(..), Handle__(..), showHandle,
19 checkHandleInvariants,
22 isReadableHandleType, isWritableHandleType, isReadWriteHandleType,
25 NewlineMode(..), Newline(..), nativeNewline,
26 universalNewlineMode, noNewlineTranslation, nativeNewlineMode
35 import GHC.IO.BufferedIO
36 import GHC.IO.Encoding.Types
48 -- ---------------------------------------------------------------------------
51 -- A Handle is represented by (a reference to) a record
52 -- containing the state of the I/O port/device. We record
53 -- the following pieces of info:
55 -- * type (read,write,closed etc.)
56 -- * the underlying file descriptor
58 -- * buffer, and spare buffers
59 -- * user-friendly name (usually the
60 -- FilePath used when IO.openFile was called)
62 -- Note: when a Handle is garbage collected, we want to flush its buffer
63 -- and close the OS file handle, so as to free up a (precious) resource.
65 -- | Haskell defines operations to read and write characters from and to files,
66 -- represented by values of type @Handle@. Each value of this type is a
67 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
68 -- with file system objects. A handle has at least the following properties:
70 -- * whether it manages input or output or both;
72 -- * whether it is /open/, /closed/ or /semi-closed/;
74 -- * whether the object is seekable;
76 -- * whether buffering is disabled, or enabled on a line or block basis;
78 -- * a buffer (whose length may be zero).
80 -- Most handles will also have a current I\/O position indicating where the next
81 -- input or output operation will occur. A handle is /readable/ if it
82 -- manages only input or both input and output; likewise, it is /writable/ if
83 -- it manages only output or both input and output. A handle is /open/ when
85 -- Once it is closed it can no longer be used for either input or output,
86 -- though an implementation cannot re-use its storage while references
87 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
88 -- produced by showing a handle is system dependent; it should include
89 -- enough information to identify the handle for debugging. A handle is
90 -- equal according to '==' only to itself; no attempt
91 -- is made to compare the internal state of different handles for equality.
94 = FileHandle -- A normal handle to a file
95 FilePath -- the file (used for error messages
99 | DuplexHandle -- A handle to a read/write stream
100 FilePath -- file for a FIFO, otherwise some
101 -- descriptive string (used for error
103 !(MVar Handle__) -- The read side
104 !(MVar Handle__) -- The write side
109 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
112 instance Eq Handle where
113 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
114 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
118 = forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) =>
121 haType :: HandleType, -- type (read/write/append etc.)
122 haByteBuffer :: !(IORef (Buffer Word8)),
123 haBufferMode :: BufferMode,
124 haLastDecode :: !(IORef (dec_state, Buffer Word8)),
125 haCharBuffer :: !(IORef (Buffer CharBufElem)), -- the current buffer
126 haBuffers :: !(IORef (BufferList CharBufElem)), -- spare buffers
127 haEncoder :: Maybe (TextEncoder enc_state),
128 haDecoder :: Maybe (TextDecoder dec_state),
129 haCodec :: Maybe TextEncoding,
130 haInputNL :: Newline,
131 haOutputNL :: Newline,
132 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
137 -- we keep a few spare buffers around in a handle to avoid allocating
138 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
139 -- same size as the main buffer.
142 | BufferListCons (RawBuffer e) (BufferList e)
144 -- Internally, we classify handles as being one
155 isReadableHandleType :: HandleType -> Bool
156 isReadableHandleType ReadHandle = True
157 isReadableHandleType ReadWriteHandle = True
158 isReadableHandleType _ = False
160 isWritableHandleType :: HandleType -> Bool
161 isWritableHandleType AppendHandle = True
162 isWritableHandleType WriteHandle = True
163 isWritableHandleType ReadWriteHandle = True
164 isWritableHandleType _ = False
166 isReadWriteHandleType :: HandleType -> Bool
167 isReadWriteHandleType ReadWriteHandle{} = True
168 isReadWriteHandleType _ = False
170 -- INVARIANTS on Handles:
172 -- * A handle *always* has a buffer, even if it is only 1 character long
173 -- (an unbuffered handle needs a 1 character buffer in order to support
174 -- hLookAhead and hIsEOF).
175 -- * In a read Handle, the byte buffer is always empty (we decode when reading)
176 -- * In a wriite Handle, the Char buffer is always empty (we encode when writing)
178 checkHandleInvariants :: Handle__ -> IO ()
180 checkHandleInvariants h_ = do
181 bbuf <- readIORef (haByteBuffer h_)
183 cbuf <- readIORef (haCharBuffer h_)
185 when (isWriteBuffer cbuf && not (isEmptyBuffer cbuf)) $
186 error ("checkHandleInvariants: char write buffer non-empty: " ++
187 summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf)
188 when (isWriteBuffer bbuf /= isWriteBuffer cbuf) $
189 error ("checkHandleInvariants: buffer modes differ: " ++
190 summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf)
193 checkHandleInvariants _ = return ()
196 -- ---------------------------------------------------------------------------
199 -- | Three kinds of buffering are supported: line-buffering,
200 -- block-buffering or no-buffering. These modes have the following
201 -- effects. For output, items are written out, or /flushed/,
202 -- from the internal buffer according to the buffer mode:
204 -- * /line-buffering/: the entire output buffer is flushed
205 -- whenever a newline is output, the buffer overflows,
206 -- a 'System.IO.hFlush' is issued, or the handle is closed.
208 -- * /block-buffering/: the entire buffer is written out whenever it
209 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
211 -- * /no-buffering/: output is written immediately, and never stored
214 -- An implementation is free to flush the buffer more frequently,
215 -- but not less frequently, than specified above.
216 -- The output buffer is emptied as soon as it has been written out.
218 -- Similarly, input occurs according to the buffer mode for the handle:
220 -- * /line-buffering/: when the buffer for the handle is not empty,
221 -- the next item is obtained from the buffer; otherwise, when the
222 -- buffer is empty, characters up to and including the next newline
223 -- character are read into the buffer. No characters are available
224 -- until the newline character is available or the buffer is full.
226 -- * /block-buffering/: when the buffer for the handle becomes empty,
227 -- the next block of data is read into the buffer.
229 -- * /no-buffering/: the next input item is read and returned.
230 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
231 -- handle may require a one-character buffer.
233 -- The default buffering mode when a handle is opened is
234 -- implementation-dependent and may depend on the file system object
235 -- which is attached to that handle.
236 -- For most implementations, physical files will normally be block-buffered
237 -- and terminals will normally be line-buffered.
240 = NoBuffering -- ^ buffering is disabled if possible.
242 -- ^ line-buffering should be enabled if possible.
243 | BlockBuffering (Maybe Int)
244 -- ^ block-buffering should be enabled if possible.
245 -- The size of the buffer is @n@ items if the argument
246 -- is 'Just' @n@ and is otherwise implementation-dependent.
247 deriving (Eq, Ord, Read, Show)
250 [note Buffering Implementation]
252 Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char
253 buffer (haCharBuffer).
255 [note Buffered Reading]
257 For read Handles, bytes are read into the byte buffer, and immediately
258 decoded into the Char buffer (see
259 GHC.IO.Handle.Internals.readTextDevice). The only way there might be
260 some data left in the byte buffer is if there is a partial multi-byte
261 character sequence that cannot be decoded into a full character.
263 Note that the buffering mode (haBufferMode) makes no difference when
264 reading data into a Handle. When reading, we can always just read all
265 the data there is available without blocking, decode it into the Char
266 buffer, and then provide it immediately to the caller.
268 [note Buffered Writing]
270 Characters are written into the Char buffer by e.g. hPutStr. At the
271 end of the operation, or when the char buffer is full, the buffer is
272 decoded to the byte buffer (see writeCharBuffer). This is so that we
273 can detect encoding errors at the right point.
275 Hence, the Char buffer is always empty between Handle operations.
279 The char buffer is always a default size (dEFAULT_CHAR_BUFFER_SIZE).
280 The byte buffer size is chosen by the underlying device (via its
281 IODevice.newBuffer). Hence the size of these buffers is not under
284 There are certain minimum sizes for these buffers imposed by the
285 library (but not checked):
287 - we must be able to buffer at least one character, so that
290 - the byte buffer must be able to store at least one encoded
291 character in the current encoding (6 bytes?)
293 - when reading, the char buffer must have room for two characters, so
294 that we can spot the \r\n sequence.
296 How do we implement hSetBuffering?
298 For reading, we have never used the user-supplied buffer size, because
299 there's no point: we always pass all available data to the reader
300 immediately. Buffering would imply waiting until a certain amount of
301 data is available, which has no advantages. So hSetBuffering is
302 essentially a no-op for read handles, except that it turns on/off raw
303 mode for the underlying device if necessary.
305 For writing, the buffering mode is handled by the write operations
306 themselves (hPutChar and hPutStr). Every write ends with
307 writeCharBuffer, which checks whether the buffer should be flushed
308 according to the current buffering mode. Additionally, we look for
309 newlines and flush if the mode is LineBuffering.
311 [note Buffer Flushing]
313 ** Flushing the Char buffer
315 We must be able to flush the Char buffer, in order to implement
316 hSetEncoding, and things like hGetBuf which want to read raw bytes.
318 Flushing the Char buffer on a write Handle is easy: it is always empty.
320 Flushing the Char buffer on a read Handle involves rewinding the byte
321 buffer to the point representing the next Char in the Char buffer.
324 - remembering the state of the byte buffer *before* the last decode
326 - re-decoding the bytes that represent the chars already read from the
327 Char buffer. This gives us the point in the byte buffer that
328 represents the *next* Char to be read.
330 In order for this to work, after readTextHandle we must NOT MODIFY THE
331 CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from
334 ** Flushing the byte buffer
336 The byte buffer can be flushed if the Char buffer has already been
337 flushed (see above). For a read Handle, flushing the byte buffer
338 means seeking the device back by the number of bytes in the buffer,
339 and hence it is only possible on a seekable Handle.
343 -- ---------------------------------------------------------------------------
344 -- Newline translation
346 -- | The representation of a newline in the external file or stream.
347 data Newline = LF -- ^ '\n'
349 deriving (Eq, Ord, Read, Show)
351 -- | Specifies the translation, if any, of newline characters between
352 -- internal Strings and the external file or stream. Haskell Strings
353 -- are assumed to represent newlines with the '\n' character; the
354 -- newline mode specifies how to translate '\n' on output, and what to
355 -- translate into '\n' on input.
357 = NewlineMode { inputNL :: Newline,
358 -- ^ the representation of newlines on input
360 -- ^ the representation of newlines on output
362 deriving (Eq, Ord, Read, Show)
364 -- | The native newline representation for the current platform: 'LF'
365 -- on Unix systems, 'CRLF' on Windows.
366 nativeNewline :: Newline
367 #ifdef mingw32_HOST_OS
373 -- | Map '\r\n' into '\n' on input, and '\n' to the native newline
374 -- represetnation on output. This mode can be used on any platform, and
375 -- works with text files using any newline convention. The downside is
376 -- that @readFile >>= writeFile@ might yield a different file.
378 -- > universalNewlineMode = NewlineMode { inputNL = CRLF,
379 -- > outputNL = nativeNewline }
381 universalNewlineMode :: NewlineMode
382 universalNewlineMode = NewlineMode { inputNL = CRLF,
383 outputNL = nativeNewline }
385 -- | Use the native newline representation on both input and output
387 -- > nativeNewlineMode = NewlineMode { inputNL = nativeNewline
388 -- > outputNL = nativeNewline }
390 nativeNewlineMode :: NewlineMode
391 nativeNewlineMode = NewlineMode { inputNL = nativeNewline,
392 outputNL = nativeNewline }
394 -- | Do no newline translation at all.
396 -- > noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }
398 noNewlineTranslation :: NewlineMode
399 noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }
401 -- ---------------------------------------------------------------------------
402 -- Show instance for Handles
404 -- handle types are 'show'n when printing error msgs, so
405 -- we provide a more user-friendly Show instance for it
406 -- than the derived one.
408 instance Show HandleType where
411 ClosedHandle -> showString "closed"
412 SemiClosedHandle -> showString "semi-closed"
413 ReadHandle -> showString "readable"
414 WriteHandle -> showString "writable"
415 AppendHandle -> showString "writable (append)"
416 ReadWriteHandle -> showString "read-writable"
418 instance Show Handle where
419 showsPrec _ (FileHandle file _) = showHandle file
420 showsPrec _ (DuplexHandle file _ _) = showHandle file
422 showHandle :: FilePath -> String -> String
423 showHandle file = showString "{handle: " . showString file . showString "}"