1 {-# OPTIONS_GHC -fno-implicit-prelude -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
45 -- ---------------------------------------------------------------------------
48 -- A Handle is represented by (a reference to) a record
49 -- containing the state of the I/O port/device. We record
50 -- the following pieces of info:
52 -- * type (read,write,closed etc.)
53 -- * the underlying file descriptor
55 -- * buffer, and spare buffers
56 -- * user-friendly name (usually the
57 -- FilePath used when IO.openFile was called)
59 -- Note: when a Handle is garbage collected, we want to flush its buffer
60 -- and close the OS file handle, so as to free up a (precious) resource.
62 -- | Haskell defines operations to read and write characters from and to files,
63 -- represented by values of type @Handle@. Each value of this type is a
64 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
65 -- with file system objects. A handle has at least the following properties:
67 -- * whether it manages input or output or both;
69 -- * whether it is /open/, /closed/ or /semi-closed/;
71 -- * whether the object is seekable;
73 -- * whether buffering is disabled, or enabled on a line or block basis;
75 -- * a buffer (whose length may be zero).
77 -- Most handles will also have a current I\/O position indicating where the next
78 -- input or output operation will occur. A handle is /readable/ if it
79 -- manages only input or both input and output; likewise, it is /writable/ if
80 -- it manages only output or both input and output. A handle is /open/ when
82 -- Once it is closed it can no longer be used for either input or output,
83 -- though an implementation cannot re-use its storage while references
84 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
85 -- produced by showing a handle is system dependent; it should include
86 -- enough information to identify the handle for debugging. A handle is
87 -- equal according to '==' only to itself; no attempt
88 -- is made to compare the internal state of different handles for equality.
90 -- GHC note: a 'Handle' will be automatically closed when the garbage
91 -- collector detects that it has become unreferenced by the program.
92 -- However, relying on this behaviour is not generally recommended:
93 -- the garbage collector is unpredictable. If possible, use explicit
94 -- an explicit 'hClose' to close 'Handle's when they are no longer
95 -- required. GHC does not currently attempt to free up file
96 -- descriptors when they have run out, it is your responsibility to
97 -- ensure that this doesn't happen.
100 = FileHandle -- A normal handle to a file
101 FilePath -- the file (used for error messages
105 | DuplexHandle -- A handle to a read/write stream
106 FilePath -- file for a FIFO, otherwise some
107 -- descriptive string (used for error
109 !(MVar Handle__) -- The read side
110 !(MVar Handle__) -- The write side
115 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
118 instance Eq Handle where
119 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
120 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
124 = forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) =>
127 haType :: HandleType, -- type (read/write/append etc.)
128 haByteBuffer :: !(IORef (Buffer Word8)),
129 haBufferMode :: BufferMode,
130 haLastDecode :: !(IORef (dec_state, Buffer Word8)),
131 haCharBuffer :: !(IORef (Buffer CharBufElem)), -- the current buffer
132 haBuffers :: !(IORef (BufferList CharBufElem)), -- spare buffers
133 haEncoder :: Maybe (TextEncoder enc_state),
134 haDecoder :: Maybe (TextDecoder dec_state),
135 haCodec :: Maybe TextEncoding,
136 haInputNL :: Newline,
137 haOutputNL :: Newline,
138 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
143 -- we keep a few spare buffers around in a handle to avoid allocating
144 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
145 -- same size as the main buffer.
148 | BufferListCons (RawBuffer e) (BufferList e)
150 -- Internally, we classify handles as being one
161 isReadableHandleType :: HandleType -> Bool
162 isReadableHandleType ReadHandle = True
163 isReadableHandleType ReadWriteHandle = True
164 isReadableHandleType _ = False
166 isWritableHandleType :: HandleType -> Bool
167 isWritableHandleType AppendHandle = True
168 isWritableHandleType WriteHandle = True
169 isWritableHandleType ReadWriteHandle = True
170 isWritableHandleType _ = False
172 isReadWriteHandleType :: HandleType -> Bool
173 isReadWriteHandleType ReadWriteHandle{} = True
174 isReadWriteHandleType _ = False
176 -- INVARIANTS on Handles:
178 -- * A handle *always* has a buffer, even if it is only 1 character long
179 -- (an unbuffered handle needs a 1 character buffer in order to support
180 -- hLookAhead and hIsEOF).
181 -- * In a read Handle, the byte buffer is always empty (we decode when reading)
182 -- * In a wriite Handle, the Char buffer is always empty (we encode when writing)
184 checkHandleInvariants :: Handle__ -> IO ()
186 checkHandleInvariants h_ = do
187 bbuf <- readIORef (haByteBuffer h_)
189 cbuf <- readIORef (haCharBuffer h_)
192 checkHandleInvariants _ = return ()
195 -- ---------------------------------------------------------------------------
198 -- | Three kinds of buffering are supported: line-buffering,
199 -- block-buffering or no-buffering. These modes have the following
200 -- effects. For output, items are written out, or /flushed/,
201 -- from the internal buffer according to the buffer mode:
203 -- * /line-buffering/: the entire output buffer is flushed
204 -- whenever a newline is output, the buffer overflows,
205 -- a 'System.IO.hFlush' is issued, or the handle is closed.
207 -- * /block-buffering/: the entire buffer is written out whenever it
208 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
210 -- * /no-buffering/: output is written immediately, and never stored
213 -- An implementation is free to flush the buffer more frequently,
214 -- but not less frequently, than specified above.
215 -- The output buffer is emptied as soon as it has been written out.
217 -- Similarly, input occurs according to the buffer mode for the handle:
219 -- * /line-buffering/: when the buffer for the handle is not empty,
220 -- the next item is obtained from the buffer; otherwise, when the
221 -- buffer is empty, characters up to and including the next newline
222 -- character are read into the buffer. No characters are available
223 -- until the newline character is available or the buffer is full.
225 -- * /block-buffering/: when the buffer for the handle becomes empty,
226 -- the next block of data is read into the buffer.
228 -- * /no-buffering/: the next input item is read and returned.
229 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
230 -- handle may require a one-character buffer.
232 -- The default buffering mode when a handle is opened is
233 -- implementation-dependent and may depend on the file system object
234 -- which is attached to that handle.
235 -- For most implementations, physical files will normally be block-buffered
236 -- and terminals will normally be line-buffered.
239 = NoBuffering -- ^ buffering is disabled if possible.
241 -- ^ line-buffering should be enabled if possible.
242 | BlockBuffering (Maybe Int)
243 -- ^ block-buffering should be enabled if possible.
244 -- The size of the buffer is @n@ items if the argument
245 -- is 'Just' @n@ and is otherwise implementation-dependent.
246 deriving (Eq, Ord, Read, Show)
249 [note Buffering Implementation]
251 Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char
252 buffer (haCharBuffer).
254 [note Buffered Reading]
256 For read Handles, bytes are read into the byte buffer, and immediately
257 decoded into the Char buffer (see
258 GHC.IO.Handle.Internals.readTextDevice). The only way there might be
259 some data left in the byte buffer is if there is a partial multi-byte
260 character sequence that cannot be decoded into a full character.
262 Note that the buffering mode (haBufferMode) makes no difference when
263 reading data into a Handle. When reading, we can always just read all
264 the data there is available without blocking, decode it into the Char
265 buffer, and then provide it immediately to the caller.
267 [note Buffered Writing]
269 Characters are written into the Char buffer by e.g. hPutStr. When the
270 buffer is full, we call writeTextDevice, which encodes the Char buffer
271 into the byte buffer, and then immediately writes it all out to the
272 underlying device. The Char buffer will always be empty afterward.
273 This might require multiple decoding/writing cycles.
277 Since the buffer mode makes no difference when reading, we can just
278 use the default buffer size for both the byte and the Char buffer.
279 Ineed, we must have room for at least one Char in the Char buffer,
280 because we have to implement hLookAhead, which requires caching a Char
281 in the Handle. Furthermore, when doing newline translation, we need
282 room for at least two Chars in the read buffer, so we can spot the
285 For writing, however, when the buffer mode is NoBuffering, we use a
286 1-element Char buffer to force flushing of the buffer after each Char
289 [note Buffer Flushing]
291 ** Flushing the Char buffer
293 We must be able to flush the Char buffer, in order to implement
294 hSetEncoding, and things like hGetBuf which want to read raw bytes.
296 Flushing the Char buffer on a write Handle is easy: just call
297 writeTextDevice to encode and write the date.
299 Flushing the Char buffer on a read Handle involves rewinding the byte
300 buffer to the point representing the next Char in the Char buffer.
303 - remembering the state of the byte buffer *before* the last decode
305 - re-decoding the bytes that represent the chars already read from the
306 Char buffer. This gives us the point in the byte buffer that
307 represents the *next* Char to be read.
309 In order for this to work, after readTextHandle we must NOT MODIFY THE
310 CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from
313 ** Flushing the byte buffer
315 The byte buffer can be flushed if the Char buffer has already been
316 flushed (see above). For a read Handle, flushing the byte buffer
317 means seeking the device back by the number of bytes in the buffer,
318 and hence it is only possible on a seekable Handle.
322 -- ---------------------------------------------------------------------------
323 -- Newline translation
325 -- | The representation of a newline in the external file or stream.
326 data Newline = LF -- ^ '\n'
330 -- | Specifies the translation, if any, of newline characters between
331 -- internal Strings and the external file or stream. Haskell Strings
332 -- are assumed to represent newlines with the '\n' character; the
333 -- newline mode specifies how to translate '\n' on output, and what to
334 -- translate into '\n' on input.
336 = NewlineMode { inputNL :: Newline,
337 -- ^ the representation of newlines on input
339 -- ^ the representation of newlines on output
343 -- | The native newline representation for the current platform: 'LF'
344 -- on Unix systems, 'CRLF' on Windows.
345 nativeNewline :: Newline
346 #ifdef mingw32_HOST_OS
352 -- | Map '\r\n' into '\n' on input, and '\n' to the native newline
353 -- represetnation on output. This mode can be used on any platform, and
354 -- works with text files using any newline convention. The downside is
355 -- that @readFile >>= writeFile@ might yield a different file.
357 -- > universalNewlineMode = NewlineMode { inputNL = CRLF,
358 -- > outputNL = nativeNewline }
360 universalNewlineMode :: NewlineMode
361 universalNewlineMode = NewlineMode { inputNL = CRLF,
362 outputNL = nativeNewline }
364 -- | Use the native newline representation on both input and output
366 -- > nativeNewlineMode = NewlineMode { inputNL = nativeNewline
367 -- > outputNL = nativeNewline }
369 nativeNewlineMode :: NewlineMode
370 nativeNewlineMode = NewlineMode { inputNL = nativeNewline,
371 outputNL = nativeNewline }
373 -- | Do no newline translation at all.
375 -- > noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }
377 noNewlineTranslation :: NewlineMode
378 noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }
380 -- ---------------------------------------------------------------------------
381 -- Show instance for Handles
383 -- handle types are 'show'n when printing error msgs, so
384 -- we provide a more user-friendly Show instance for it
385 -- than the derived one.
387 instance Show HandleType where
390 ClosedHandle -> showString "closed"
391 SemiClosedHandle -> showString "semi-closed"
392 ReadHandle -> showString "readable"
393 WriteHandle -> showString "writable"
394 AppendHandle -> showString "writable (append)"
395 ReadWriteHandle -> showString "read-writable"
397 instance Show Handle where
398 showsPrec _ (FileHandle file _) = showHandle file
399 showsPrec _ (DuplexHandle file _ _) = showHandle file
401 showHandle :: FilePath -> String -> String
402 showHandle file = showString "{handle: " . showString file . showString "}"