on cfd77bd help sign in
434 lines 16 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
7#include "inline.hs"
9-- |
10-- Module : Streamly.FileSystem.Handle
11-- Copyright : (c) 2018 Harendra Kumar
12--
13-- License : BSD3
14-- Maintainer : harendra.kumar@gmail.com
15-- Stability : experimental
16-- Portability : GHC
17--
18-- Read and write streams and arrays to and from file handles. File handle IO
19-- APIs are quite similar to "Streamly.Mem.Array" read write APIs. In that
20-- regard, arrays can be considered as in-memory files or files can be
21-- considered as on-disk arrays. IO APIs are divided into two categories,
22-- sequential streaming IO APIs and random access IO APIs. Control over the
23-- file reading and writing behavior in terms of buffering, encoding, decoding
24-- is in the hands of the programmer, the 'TextEncoding', 'NewLineMode', and
25-- 'Buffering' options of the underlying handle provided by GHC are not needed
26-- and ignored.
27--
28-- > import qualified Streamly.FileSystem.Handle as FH
29--
31module Streamly.FileSystem.Handle
32 (
33 -- * Streaming IO
34 -- | Stream data to or from a file or device sequentially. When reading,
35 -- the stream is lazy and generated on-demand as the consumer consumes it.
36 -- Read IO requests to the IO device are performed in chunks limited to a
37 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
38 -- documentation. One IO request may or may not read the full
39 -- chunk. If the whole stream is not consumed, it is possible that we may
40 -- read slightly more from the IO device than what the consumer needed.
41 -- Unless specified otherwise in the API, writes are collected into chunks
42 -- of @defaultChunkSize@ before they are written to the IO device.
44 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
45 -- including disks, files, memory devices, terminals, pipes, sockets and
46 -- fifos. While random access APIs work only for files or devices that have
47 -- random access or seek capability for example disks, memory devices.
48 -- Devices like terminals, pipes, sockets and fifos do not have random
49 -- access capability.
51 -- ** Read Handle to Stream
52 read
53 -- , readUtf8
54 -- , readLines
55 -- , readFrames
56 -- , readByChunks
58 -- -- * Array Read
59 -- , readArrayUpto
60 -- , readArrayOf
62 , readArraysUpto
63 -- , readArraysOf
64 , readArrays
66 -- ** Write File from Stream
67 , write
68 -- , writeUtf8
69 -- , writeUtf8ByLines
70 -- , writeByFrames
71 , writeByChunks
73 -- -- * Array Write
74 , writeArray
75 , writeArrays
77 -- -- * Random Access (Seek)
78 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
79 -- files that have random access or seek capability. This type of devices
80 -- include disks, files, memory devices and exclude terminals, pipes,
81 -- sockets and fifos.
82 --
83 -- , readIndex
84 -- , readSlice
85 -- , readSliceRev
86 -- , readAt -- read from a given position to th end of file
87 -- , readSliceArrayUpto
88 -- , readSliceArrayOf
90 -- , writeIndex
91 -- , writeSlice
92 -- , writeSliceRev
93 -- , writeAt -- start writing at the given position
94 -- , writeSliceArray
95 )
96where
98import Control.Monad.IO.Class (MonadIO(..))
99import Data.Word (Word8)
100import Foreign.ForeignPtr (withForeignPtr)
101import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
102import Foreign.Ptr (minusPtr, plusPtr)
103import Foreign.Storable (Storable(..))
104import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
105import System.IO (Handle, hGetBufSome, hPutBuf)
106import Prelude hiding (read)
108import Streamly.Mem.Array.Types (Array(..))
109import Streamly.Streams.Serial (SerialT)
110import Streamly.Streams.StreamK.Type (IsStream, mkStream)
111-- import Streamly.Fold (Fold)
112-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
114import qualified Streamly.Mem.Array as A
115import qualified Streamly.Mem.Array.Types as A hiding (flattenArrays)
116import qualified Streamly.Prelude as S
118-------------------------------------------------------------------------------
119-- References
120-------------------------------------------------------------------------------
121--
122-- The following references may be useful to build an understanding about the
123-- file API design:
124--
125-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
126-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
127-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
128-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
129-- https://www.w3.org/TR/FileAPI/ for http file API.
131-------------------------------------------------------------------------------
132-- Array IO (Input)
133-------------------------------------------------------------------------------
135-- | Read a 'ByteArray' from a file handle. If no data is available on the
136-- handle it blocks until some data becomes available. If data is available
137-- then it immediately returns that data without blocking. It reads a maximum
138-- of up to the size requested.
139{-# INLINABLE readArrayUpto #-}
140readArrayUpto :: Int -> Handle -> IO (Array Word8)
141readArrayUpto size h = do
142 ptr <- mallocPlainForeignPtrBytes size
143 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
144 withForeignPtr ptr $ \p -> do
145 n <- hGetBufSome h p size
146 let v = Array
147 { aStart = ptr
148 , aEnd = p `plusPtr` n
149 , aBound = p `plusPtr` size
150 }
151 -- XXX shrink only if the diff is significant
152 A.shrinkToFit v
154-------------------------------------------------------------------------------
155-- Array IO (output)
156-------------------------------------------------------------------------------
158-- | Write an Array to a file handle.
159--
160-- @since 0.7.0
161{-# INLINABLE writeArray #-}
162writeArray :: Storable a => Handle -> Array a -> IO ()
163writeArray _ arr | A.length arr == 0 = return ()
164writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
165 where
166 aLen =
167 let p = unsafeForeignPtrToPtr aStart
168 in aEnd `minusPtr` p
170-------------------------------------------------------------------------------
171-- Stream of Arrays IO
172-------------------------------------------------------------------------------
174-- | @readArraysUpto size h@ reads a stream of arrays from file handle @h@.
175-- The maximum size of a single array is specified by @size@. The actual size
176-- read may be less than or equal to @size@.
177{-# INLINABLE readArraysUpto #-}
178readArraysUpto :: (IsStream t, MonadIO m)
179 => Int -> Handle -> t m (Array Word8)
180readArraysUpto size h = go
181 where
182 -- XXX use cons/nil instead
183 go = mkStream $ \_ yld _ stp -> do
184 arr <- liftIO $ readArrayUpto size h
185 if A.length arr == 0
186 then stp
187 else yld arr go
189-- XXX read 'Array a' instead of Word8
190--
191-- | @readArrays h@ reads a stream of arrays from file handle @h@.
192-- The maximum size of a single array is limited to @defaultChunkSize@.
193-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
194-- on the 'Handle'.
195--
196-- > readArrays = readArraysUpto defaultChunkSize
197--
198-- @since 0.7.0
199{-# INLINE readArrays #-}
200readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
201readArrays = readArraysUpto A.defaultChunkSize
203-------------------------------------------------------------------------------
204-- Read File to Stream
205-------------------------------------------------------------------------------
207-- TODO for concurrent streams implement readahead IO. We can send multiple
208-- read requests at the same time. For serial case we can use async IO. We can
209-- also control the read throughput in mbps or IOPS.
211{-
212-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file
213-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
214-- as soon as EOF is encountered.
215--
216{-# INLINE readByChunksUpto #-}
217readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
218readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
219-}
221-- TODO
222-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
223--
224-- > read = 'readByChunks' A.defaultChunkSize
225-- | Generate a stream of elements of the given type from a file 'Handle'. The
226-- stream ends when EOF is encountered.
227--
228-- @since 0.7.0
229{-# INLINE read #-}
230read :: (IsStream t, MonadIO m) => Handle -> t m Word8
231read = A.flattenArrays . readArrays
233-------------------------------------------------------------------------------
234-- Writing
235-------------------------------------------------------------------------------
237-- | Write a stream of arrays to a handle.
238--
239-- @since 0.7.0
240{-# INLINE writeArrays #-}
241writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
242writeArrays h m = S.mapM_ (liftIO . writeArray h) m
244-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
245--
246-- XXX test this
247-- Note that if you use a chunk size less than 8K (GHC's default buffer
248-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
249-- do not want buffering to occur at GHC level as well. Same thing applies to
250-- writes as well.
252-- | Like 'write' but provides control over the write buffer. Output will
253-- be written to the IO device as soon as we collect the specified number of
254-- input elements.
255--
256-- @since 0.7.0
257{-# INLINE writeByChunks #-}
258writeByChunks :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
259writeByChunks n h m = writeArrays h $ A.arraysOf n m
261-- > write = 'writeByChunks' A.defaultChunkSize
262--
263-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
264-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
265-- depends on the 'IOMode' and the current seek position of the handle.
266--
267-- @since 0.7.0
268{-# INLINE write #-}
269write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
270write = writeByChunks A.defaultChunkSize
272{-
273{-# INLINE write #-}
274write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
275write = toHandleWith A.defaultChunkSize
276-}
278-- XXX mmap a file into an array. This could be useful for in-place operations
279-- on a file. For example, we can quicksort the contents of a file by mmapping
280-- it.
282-------------------------------------------------------------------------------
283-- IO with encoding/decoding Unicode characters
284-------------------------------------------------------------------------------
286{-
287-- |
288-- > readUtf8 = decodeUtf8 . read
289--
290-- Read a UTF8 encoded stream of unicode characters from a file handle.
291--
292-- @since 0.7.0
293{-# INLINE readUtf8 #-}
294readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
295readUtf8 = decodeUtf8 . read
297-- |
298-- > writeUtf8 h s = write h $ encodeUtf8 s
299--
300-- Encode a stream of unicode characters to UTF8 and write it to the given file
301-- handle. Default block buffering applies to the writes.
302--
303-- @since 0.7.0
304{-# INLINE writeUtf8 #-}
305writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
306writeUtf8 h s = write h $ encodeUtf8 s
308-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
309-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
310-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
311-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
312-- option.
313--
314-- @since 0.7.0
315{-# INLINE writeUtf8ByLines #-}
316writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
317writeUtf8ByLines = undefined
319-- | Read UTF-8 lines from a file handle and apply the specified fold to each
320-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
321--
322-- @since 0.7.0
323{-# INLINE readLines #-}
324readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
325readLines h f = foldLines (readUtf8 h) f
327-------------------------------------------------------------------------------
328-- Framing on a sequence
329-------------------------------------------------------------------------------
331-- | Read a stream from a file handle and split it into frames delimited by
332-- the specified sequence of elements. The supplied fold is applied on each
333-- frame.
334--
335-- @since 0.7.0
336{-# INLINE readFrames #-}
337readFrames :: (IsStream t, MonadIO m, Storable a)
338 => Array a -> Handle -> Fold m a b -> t m b
339readFrames = undefined -- foldFrames . read
341-- | Write a stream to the given file handle buffering up to frames separated
342-- by the given sequence or up to a maximum of @defaultChunkSize@.
343--
344-- @since 0.7.0
345{-# INLINE writeByFrames #-}
346writeByFrames :: (IsStream t, MonadIO m, Storable a)
347 => Array a -> Handle -> t m a -> m ()
348writeByFrames = undefined
350-------------------------------------------------------------------------------
351-- Random Access IO (Seek)
352-------------------------------------------------------------------------------
354-- XXX handles could be shared, so we may not want to use the handle state at
355-- all for these APIs. we can use pread and pwrite instead. On windows we will
356-- need to use readFile/writeFile with an offset argument.
358-------------------------------------------------------------------------------
360-- | Read the element at the given index treating the file as an array.
361--
362-- @since 0.7.0
363{-# INLINE readIndex #-}
364readIndex :: Storable a => Handle -> Int -> Maybe a
365readIndex arr i = undefined
367-- NOTE: To represent a range to read we have chosen (start, size) instead of
368-- (start, end). This helps in removing the ambiguity of whether "end" is
369-- included in the range or not.
370--
371-- We could avoid specifying the range to be read and instead use "take size"
372-- on the stream, but it may end up reading more and then consume it partially.
374-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
375-- from @handle@ starting at the offset @pos@ from the beginning of the file.
376--
377-- Reads are performed in chunks of size @chunkSize@. For block devices, to
378-- avoid reading partial blocks @chunkSize@ must align with the block size of
379-- the underlying device. If the underlying block size is unknown, it is a good
380-- idea to keep it a multiple 4KiB. This API ensures that the start of each
381-- chunk is aligned with @chunkSize@ from second chunk onwards.
382--
383{-# INLINE readSliceWith #-}
384readSliceWith :: (IsStream t, MonadIO m, Storable a)
385 => Int -> Handle -> Int -> Int -> t m a
386readSliceWith chunkSize h pos len = undefined
388-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
389-- at index @i@ and reading up to @count@ elements in the forward direction
390-- ending at the index @i + count - 1@.
391--
392-- @since 0.7.0
393{-# INLINE readSlice #-}
394readSlice :: (IsStream t, MonadIO m, Storable a)
395 => Handle -> Int -> Int -> t m a
396readSlice = readSliceWith A.defaultChunkSize
398-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
399-- at index @i@ and reading up to @count@ elements in the reverse direction
400-- ending at the index @i - count + 1@.
401--
402-- @since 0.7.0
403{-# INLINE readSliceRev #-}
404readSliceRev :: (IsStream t, MonadIO m, Storable a)
405 => Handle -> Int -> Int -> t m a
406readSliceRev h i count = undefined
408-- | Write the given element at the given index in the file.
409--
410-- @since 0.7.0
411{-# INLINE writeIndex #-}
412writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
413writeIndex h i a = undefined
415-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
416-- starting at index @i@ and writing up to @count@ elements in the forward
417-- direction ending at the index @i + count - 1@.
418--
419-- @since 0.7.0
420{-# INLINE writeSlice #-}
421writeSlice :: (IsStream t, Monad m, Storable a)
422 => Handle -> Int -> Int -> t m a -> m ()
423writeSlice h i len s = undefined
425-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
426-- starting at index @i@ and writing up to @count@ elements in the reverse
427-- direction ending at the index @i - count + 1@.
428--
429-- @since 0.7.0
430{-# INLINE writeSliceRev #-}
431writeSliceRev :: (IsStream t, Monad m, Storable a)
432 => Handle -> Int -> Int -> t m a -> m ()
433writeSliceRev arr i len s = undefined
434-}