2 {-# LANGUAGE RankNTypes #-}
3 {-# LANGUAGE TypeOperators #-}
6 module Distribution
.Utils
.IOData
7 ( -- * 'IOData' & 'IODataMode' type
10 , KnownIODataMode
(..)
16 import qualified Data
.ByteString
.Lazy
as LBS
17 import Distribution
.Compat
.Prelude
hiding (null)
18 import qualified System
.IO
19 import qualified Prelude
21 -- | Represents either textual or binary data passed via I/O functions
22 -- which support binary/text mode
26 = -- | How Text gets encoded is usually locale-dependent.
28 |
-- | Raw binary which gets read/written in binary mode.
29 IODataBinary LBS
.ByteString
31 -- | Applies a function polymorphic over 'IODataMode' to an 'IOData' value.
32 withIOData
:: IOData
-> (forall mode
. IODataMode mode
-> mode
-> r
) -> r
33 withIOData
(IODataText str
) k
= k IODataModeText str
34 withIOData
(IODataBinary lbs
) k
= k IODataModeBinary lbs
36 -- | Test whether 'IOData' is empty
37 null :: IOData
-> Bool
38 null (IODataText s
) = Prelude
.null s
39 null (IODataBinary b
) = LBS
.null b
41 instance NFData IOData
where
42 rnf
(IODataText s
) = rnf s
43 rnf
(IODataBinary lbs
) = rnf lbs
46 class NFData mode
=> KnownIODataMode mode
where
47 -- | 'IOData' Wrapper for 'System.IO.hGetContents'
49 -- __Note__: This operation uses lazy I/O. Use 'NFData' to force all
50 -- data to be read and consequently the internal file handle to be
52 hGetIODataContents
:: System
.IO.Handle -> Prelude
.IO mode
54 toIOData
:: mode
-> IOData
55 iodataMode
:: IODataMode mode
57 -- | Phantom-typed GADT representation of the mode of 'IOData', containing no
61 data IODataMode mode
where
62 IODataModeText
:: IODataMode
String
63 IODataModeBinary
:: IODataMode LBS
.ByteString
65 instance a ~
Char => KnownIODataMode
[a
] where
66 hGetIODataContents h
= do
67 System
.IO.hSetBinaryMode h
False
68 System
.IO.hGetContents h
71 iodataMode
= IODataModeText
73 instance KnownIODataMode LBS
.ByteString
where
74 hGetIODataContents h
= do
75 System
.IO.hSetBinaryMode h
True
78 toIOData
= IODataBinary
79 iodataMode
= IODataModeBinary
81 -- | 'IOData' Wrapper for 'System.IO.hPutStr' and 'System.IO.hClose'
83 -- This is the dual operation ot 'hGetIODataContents',
84 -- and consequently the handle is closed with `hClose`.
86 -- /Note:/ this performs lazy-IO.
89 hPutContents
:: System
.IO.Handle -> IOData
-> Prelude
.IO ()
90 hPutContents h
(IODataText c
) = do
91 System
.IO.hSetBinaryMode h
False
94 hPutContents h
(IODataBinary c
) = do
95 System
.IO.hSetBinaryMode h
True