on b9e99db help sign in
477 lines 18 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.Memory.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.
22--
23-- Control over file reading and writing behavior in terms of buffering,
24-- encoding, decoding is in the hands of the programmer, the 'TextEncoding',
25-- 'NewLineMode', and 'Buffering' options of the underlying handle provided by
26-- GHC are not needed and ignored.
27--
28-- > import qualified Streamly.FileSystem.Handle as FH
29--
31-- IO APIs are divided into two categories, sequential streaming IO APIs and
32-- random access IO APIs.
34module Streamly.FileSystem.Handle
35 (
36 -- * Sequential/Streaming IO
37 -- | Stream data to or from a file or device sequentially. When reading,
38 -- the stream is lazy and generated on-demand as the consumer consumes it.
39 -- Read IO requests to the IO device are performed in chunks limited to a
40 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
41 -- documentation. One IO request may or may not read the full
42 -- chunk. If the whole stream is not consumed, it is possible that we may
43 -- read slightly more from the IO device than what the consumer needed.
44 -- Unless specified otherwise in the API, writes are collected into chunks
45 -- of @defaultChunkSize@ before they are written to the IO device.
47 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
48 -- including disks, files, memory devices, terminals, pipes, sockets and
49 -- fifos. While random access APIs work only for files or devices that have
50 -- random access or seek capability for example disks, memory devices.
51 -- Devices like terminals, pipes, sockets and fifos do not have random
52 -- access capability.
54 -- ** Read From Handle
55 -- | 'TextEncoding', 'NewLineMode', and 'Buffering' options of the
56 -- underlying handle are ignored. The read occurs from the current seek
57 -- position of the file handle. The stream ends as soon as EOF is
58 -- encountered.
60 read
61 -- , readUtf8
62 -- , readLines
63 -- , readFrames
64 , readInChunksOf
66 -- -- * Array Read
67 -- , readArrayUpto
68 -- , readArrayOf
70 , readArraysOf
71 -- , readArraysOf
72 , readArrays
74 -- ** Write to Handle
75 -- | 'TextEncoding', 'NewLineMode', and 'Buffering' options of the
76 -- underlying handle are ignored. The write occurs from the current seek
77 -- position of the file handle. The write behavior depends on the 'IOMode'
78 -- of the handle.
79 --
80 , write
81 -- , writeUtf8
82 -- , writeUtf8ByLines
83 -- , writeByFrames
84 , writeInChunksOf
86 -- -- * Array Write
87 , writeArray
88 , writeArrays
89 , writeArraysInChunksOf
91 -- -- * Random Access (Seek)
92 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
93 -- files that have random access or seek capability. This type of devices
94 -- include disks, files, memory devices and exclude terminals, pipes,
95 -- sockets and fifos.
96 --
97 -- , readIndex
98 -- , readSlice
99 -- , readSliceRev
100 -- , readAt -- read from a given position to th end of file
101 -- , readSliceArrayUpto
102 -- , readSliceArrayOf
104 -- , writeIndex
105 -- , writeSlice
106 -- , writeSliceRev
107 -- , writeAt -- start writing at the given position
108 -- , writeSliceArray
109 )
110where
112import Control.Monad.IO.Class (MonadIO(..))
113import Data.Word (Word8)
114import Foreign.ForeignPtr (withForeignPtr)
115import Foreign.Ptr (plusPtr)
116import Foreign.Storable (Storable(..))
117import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
118import System.IO (Handle, hGetBufSome)
119import Prelude hiding (read)
121import Streamly.FileSystem.Handle.Internal (writeArray)
122import Streamly.Memory.Array.Types (Array(..), writeNUnsafe)
123import Streamly.Streams.StreamK.Type (IsStream, mkStream)
124import Streamly.Memory.Array.Types
125 (defaultChunkSize, shrinkToFit, lpackArraysChunksOf)
126import Streamly.Fold (Fold)
127-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
129import qualified Streamly.Fold as FL
130import qualified Streamly.Fold.Types as FL
131import qualified Streamly.Memory.Array as A
132import qualified Streamly.Streams.StreamD.Type as D
134-------------------------------------------------------------------------------
135-- References
136-------------------------------------------------------------------------------
137--
138-- The following references may be useful to build an understanding about the
139-- file API design:
140--
141-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
142-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
143-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
144-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
145-- https://www.w3.org/TR/FileAPI/ for http file API.
147-------------------------------------------------------------------------------
148-- Array IO (Input)
149-------------------------------------------------------------------------------
151-- | Read a 'ByteArray' from a file handle. If no data is available on the
152-- handle it blocks until some data becomes available. If data is available
153-- then it immediately returns that data without blocking. It reads a maximum
154-- of up to the size requested.
155{-# INLINABLE readArrayUpto #-}
156readArrayUpto :: Int -> Handle -> IO (Array Word8)
157readArrayUpto size h = do
158 ptr <- mallocPlainForeignPtrBytes size
159 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
160 withForeignPtr ptr $ \p -> do
161 n <- hGetBufSome h p size
162 let v = Array
163 { aStart = ptr
164 , aEnd = p `plusPtr` n
165 , aBound = p `plusPtr` size
166 }
167 -- XXX shrink only if the diff is significant
168 shrinkToFit v
170-------------------------------------------------------------------------------
171-- Stream of Arrays IO
172-------------------------------------------------------------------------------
174-- | @readArraysOf 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 _readArraysOf #-}
178_readArraysOf :: (IsStream t, MonadIO m)
179 => Int -> Handle -> t m (Array Word8)
180_readArraysOf 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-- | @readArraysOf size handle@ reads a stream of arrays from the file
190-- handle @handle@. The maximum size of a single array is limited to @size@.
191-- The actual size read may be less than or equal to @size@.
192--
193-- @since 0.7.0
194{-# INLINE_NORMAL readArraysOf #-}
195readArraysOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
196readArraysOf size h = D.fromStreamD (D.Stream step ())
197 where
198 {-# INLINE_LATE step #-}
199 step _ _ = do
200 arr <- liftIO $ readArrayUpto size h
201 return $
202 case A.length arr of
203 0 -> D.Stop
204 _ -> D.Yield arr ()
206-- XXX read 'Array a' instead of Word8
207--
208-- | @readArrays handle@ reads a stream of arrays from the specified file
209-- handle. The maximum size of a single array is limited to
210-- @defaultChunkSize@. The actual size read may be less than or equal to
211-- @defaultChunkSize@.
212--
213-- > readArrays = readArraysOf defaultChunkSize
214--
215-- @since 0.7.0
216{-# INLINE readArrays #-}
217readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
218readArrays = readArraysOf defaultChunkSize
220-------------------------------------------------------------------------------
221-- Read File to Stream
222-------------------------------------------------------------------------------
224-- TODO for concurrent streams implement readahead IO. We can send multiple
225-- read requests at the same time. For serial case we can use async IO. We can
226-- also control the read throughput in mbps or IOPS.
228-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
229-- handle, reads are performed in chunks of up to @chunkSize@.
230--
231-- @since 0.7.0
232{-# INLINE readInChunksOf #-}
233readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
234readInChunksOf chunkSize h = A.concat $ readArraysOf chunkSize h
236-- TODO
237-- Generate a stream of elements of the given type from a file 'Handle'.
238-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
239--
240-- > read = 'readInChunksOf' A.defaultChunkSize
241-- | Generate a byte stream from a file 'Handle'.
242--
243-- @since 0.7.0
244{-# INLINE read #-}
245read :: (IsStream t, MonadIO m) => Handle -> t m Word8
246read = A.concat . readArrays
248-------------------------------------------------------------------------------
249-- Writing
250-------------------------------------------------------------------------------
252-- | Write a stream of arrays to a handle.
253--
254-- @since 0.7.0
255{-# INLINE writeArrays #-}
256writeArrays :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
257writeArrays h = FL.drainBy (liftIO . writeArray h)
259-- | @writeArraysInChunksOf chunkSize handle@ writes a stream of arrays
260-- to @handle@ after coalescing the adjacent arrays in chunks of @chunkSize@.
261-- We never split an array, if a single array is bigger than the specified size
262-- it emitted as it is. Multiple arrays are coalesed as long as the total size
263-- remains below the specified size.
264--
265-- @since 0.7.0
266{-# INLINE writeArraysInChunksOf #-}
267writeArraysInChunksOf :: (MonadIO m, Storable a)
268 => Int -> Handle -> Fold m (Array a) ()
269writeArraysInChunksOf n h = lpackArraysChunksOf n (writeArrays h)
271-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
272--
273-- XXX test this
274-- Note that if you use a chunk size less than 8K (GHC's default buffer
275-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
276-- do not want buffering to occur at GHC level as well. Same thing applies to
277-- writes as well.
279-- | @writeInChunksOf chunkSize handle@ writes the input stream to @handle@ in
280-- chunks of @chunkSize@. A write is performed to the IO device as soon as we
281-- collect the required input size.
282--
283-- @since 0.7.0
284{-# INLINE writeInChunksOf #-}
285writeInChunksOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
286writeInChunksOf n h = FL.lchunksOf n (writeNUnsafe n) (writeArrays h)
288-- > write = 'writeInChunksOf' A.defaultChunkSize
289--
290-- | Write a byte stream to a file handle. Accumulates the input in chunks of
291-- up to 'A.defaultChunkSize' before writing.
292--
293-- @since 0.7.0
294{-# INLINE write #-}
295write :: MonadIO m => Handle -> Fold m Word8 ()
296write = writeInChunksOf defaultChunkSize
298{-
299{-# INLINE write #-}
300write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
301write = toHandleWith A.defaultChunkSize
302-}
304-- XXX mmap a file into an array. This could be useful for in-place operations
305-- on a file. For example, we can quicksort the contents of a file by mmapping
306-- it.
308-------------------------------------------------------------------------------
309-- IO with encoding/decoding Unicode characters
310-------------------------------------------------------------------------------
312{-
313-- |
314-- > readUtf8 = decodeUtf8 . read
315--
316-- Read a UTF8 encoded stream of unicode characters from a file handle.
317--
318-- @since 0.7.0
319{-# INLINE readUtf8 #-}
320readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
321readUtf8 = decodeUtf8 . read
323-- |
324-- > writeUtf8 h s = write h $ encodeUtf8 s
325--
326-- Encode a stream of unicode characters to UTF8 and write it to the given file
327-- handle. Default block buffering applies to the writes.
328--
329-- @since 0.7.0
330{-# INLINE writeUtf8 #-}
331writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
332writeUtf8 h s = write h $ encodeUtf8 s
334-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
335-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
336-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
337-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
338-- option.
339--
340-- @since 0.7.0
341{-# INLINE writeUtf8ByLines #-}
342writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
343writeUtf8ByLines = undefined
345-- | Read UTF-8 lines from a file handle and apply the specified fold to each
346-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
347--
348-- @since 0.7.0
349{-# INLINE readLines #-}
350readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
351readLines h f = foldLines (readUtf8 h) f
353-------------------------------------------------------------------------------
354-- Framing on a sequence
355-------------------------------------------------------------------------------
357-- | Read a stream from a file handle and split it into frames delimited by
358-- the specified sequence of elements. The supplied fold is applied on each
359-- frame.
360--
361-- @since 0.7.0
362{-# INLINE readFrames #-}
363readFrames :: (IsStream t, MonadIO m, Storable a)
364 => Array a -> Handle -> Fold m a b -> t m b
365readFrames = undefined -- foldFrames . read
367-- | Write a stream to the given file handle buffering up to frames separated
368-- by the given sequence or up to a maximum of @defaultChunkSize@.
369--
370-- @since 0.7.0
371{-# INLINE writeByFrames #-}
372writeByFrames :: (IsStream t, MonadIO m, Storable a)
373 => Array a -> Handle -> t m a -> m ()
374writeByFrames = undefined
376-------------------------------------------------------------------------------
377-- Framing by time
378-------------------------------------------------------------------------------
380-- | Write collecting the input in sessions of n seconds or if chunkSize
381-- gets exceeded.
382{-# INLINE writeByChunksOrSessionsOf #-}
383writeByChunksOrSessionsOf :: MonadIO m
384 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
385writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
387-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
388-- gets exceeded.
389{-# INLINE writeBySessionsOf #-}
390writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
391writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
393-------------------------------------------------------------------------------
394-- Random Access IO (Seek)
395-------------------------------------------------------------------------------
397-- XXX handles could be shared, so we may not want to use the handle state at
398-- all for these APIs. we can use pread and pwrite instead. On windows we will
399-- need to use readFile/writeFile with an offset argument.
401-------------------------------------------------------------------------------
403-- | Read the element at the given index treating the file as an array.
404--
405-- @since 0.7.0
406{-# INLINE readIndex #-}
407readIndex :: Storable a => Handle -> Int -> Maybe a
408readIndex arr i = undefined
410-- NOTE: To represent a range to read we have chosen (start, size) instead of
411-- (start, end). This helps in removing the ambiguity of whether "end" is
412-- included in the range or not.
413--
414-- We could avoid specifying the range to be read and instead use "take size"
415-- on the stream, but it may end up reading more and then consume it partially.
417-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
418-- from @handle@ starting at the offset @pos@ from the beginning of the file.
419--
420-- Reads are performed in chunks of size @chunkSize@. For block devices, to
421-- avoid reading partial blocks @chunkSize@ must align with the block size of
422-- the underlying device. If the underlying block size is unknown, it is a good
423-- idea to keep it a multiple 4KiB. This API ensures that the start of each
424-- chunk is aligned with @chunkSize@ from second chunk onwards.
425--
426{-# INLINE readSliceWith #-}
427readSliceWith :: (IsStream t, MonadIO m, Storable a)
428 => Int -> Handle -> Int -> Int -> t m a
429readSliceWith chunkSize h pos len = undefined
431-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
432-- at index @i@ and reading up to @count@ elements in the forward direction
433-- ending at the index @i + count - 1@.
434--
435-- @since 0.7.0
436{-# INLINE readSlice #-}
437readSlice :: (IsStream t, MonadIO m, Storable a)
438 => Handle -> Int -> Int -> t m a
439readSlice = readSliceWith A.defaultChunkSize
441-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
442-- at index @i@ and reading up to @count@ elements in the reverse direction
443-- ending at the index @i - count + 1@.
444--
445-- @since 0.7.0
446{-# INLINE readSliceRev #-}
447readSliceRev :: (IsStream t, MonadIO m, Storable a)
448 => Handle -> Int -> Int -> t m a
449readSliceRev h i count = undefined
451-- | Write the given element at the given index in the file.
452--
453-- @since 0.7.0
454{-# INLINE writeIndex #-}
455writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
456writeIndex h i a = undefined
458-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
459-- starting at index @i@ and writing up to @count@ elements in the forward
460-- direction ending at the index @i + count - 1@.
461--
462-- @since 0.7.0
463{-# INLINE writeSlice #-}
464writeSlice :: (IsStream t, Monad m, Storable a)
465 => Handle -> Int -> Int -> t m a -> m ()
466writeSlice h i len s = undefined
468-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
469-- starting at index @i@ and writing up to @count@ elements in the reverse
470-- direction ending at the index @i - count + 1@.
471--
472-- @since 0.7.0
473{-# INLINE writeSliceRev #-}
474writeSliceRev :: (IsStream t, Monad m, Storable a)
475 => Handle -> Int -> Int -> t m a -> m ()
476writeSliceRev arr i len s = undefined
477-}