on e1ba45a help sign in
478 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.Internal.FileSystem.Handle (writeArray)
122import Streamly.Internal.Memory.Array.Types (Array(..), writeNUnsafe)
123import Streamly.Streams.StreamK.Type (IsStream, mkStream)
124import Streamly.Internal.Memory.Array.Types
125 (defaultChunkSize, shrinkToFit, lpackArraysChunksOf)
126import Streamly.Data.Fold (Fold)
127-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
129import qualified Streamly.Data.Fold as FL
130import qualified Streamly.Internal.Data.Fold.Types as FL
131import qualified Streamly.Memory.Array as A
132import qualified Streamly.Internal.Memory.ArrayStream as AS
133import qualified Streamly.Streams.StreamD.Type as D
135-------------------------------------------------------------------------------
136-- References
137-------------------------------------------------------------------------------
138--
139-- The following references may be useful to build an understanding about the
140-- file API design:
141--
142-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
143-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
144-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
145-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
146-- https://www.w3.org/TR/FileAPI/ for http file API.
148-------------------------------------------------------------------------------
149-- Array IO (Input)
150-------------------------------------------------------------------------------
152-- | Read a 'ByteArray' from a file handle. If no data is available on the
153-- handle it blocks until some data becomes available. If data is available
154-- then it immediately returns that data without blocking. It reads a maximum
155-- of up to the size requested.
156{-# INLINABLE readArrayUpto #-}
157readArrayUpto :: Int -> Handle -> IO (Array Word8)
158readArrayUpto size h = do
159 ptr <- mallocPlainForeignPtrBytes size
160 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
161 withForeignPtr ptr $ \p -> do
162 n <- hGetBufSome h p size
163 let v = Array
164 { aStart = ptr
165 , aEnd = p `plusPtr` n
166 , aBound = p `plusPtr` size
167 }
168 -- XXX shrink only if the diff is significant
169 shrinkToFit v
171-------------------------------------------------------------------------------
172-- Stream of Arrays IO
173-------------------------------------------------------------------------------
175-- | @readArraysOf size h@ reads a stream of arrays from file handle @h@.
176-- The maximum size of a single array is specified by @size@. The actual size
177-- read may be less than or equal to @size@.
178{-# INLINABLE _readArraysOf #-}
179_readArraysOf :: (IsStream t, MonadIO m)
180 => Int -> Handle -> t m (Array Word8)
181_readArraysOf size h = go
182 where
183 -- XXX use cons/nil instead
184 go = mkStream $ \_ yld _ stp -> do
185 arr <- liftIO $ readArrayUpto size h
186 if A.length arr == 0
187 then stp
188 else yld arr go
190-- | @readArraysOf size handle@ reads a stream of arrays from the file
191-- handle @handle@. The maximum size of a single array is limited to @size@.
192-- The actual size read may be less than or equal to @size@.
193--
194-- @since 0.7.0
195{-# INLINE_NORMAL readArraysOf #-}
196readArraysOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
197readArraysOf size h = D.fromStreamD (D.Stream step ())
198 where
199 {-# INLINE_LATE step #-}
200 step _ _ = do
201 arr <- liftIO $ readArrayUpto size h
202 return $
203 case A.length arr of
204 0 -> D.Stop
205 _ -> D.Yield arr ()
207-- XXX read 'Array a' instead of Word8
208--
209-- | @readArrays handle@ reads a stream of arrays from the specified file
210-- handle. The maximum size of a single array is limited to
211-- @defaultChunkSize@. The actual size read may be less than or equal to
212-- @defaultChunkSize@.
213--
214-- > readArrays = readArraysOf defaultChunkSize
215--
216-- @since 0.7.0
217{-# INLINE readArrays #-}
218readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
219readArrays = readArraysOf defaultChunkSize
221-------------------------------------------------------------------------------
222-- Read File to Stream
223-------------------------------------------------------------------------------
225-- TODO for concurrent streams implement readahead IO. We can send multiple
226-- read requests at the same time. For serial case we can use async IO. We can
227-- also control the read throughput in mbps or IOPS.
229-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
230-- handle, reads are performed in chunks of up to @chunkSize@.
231--
232-- @since 0.7.0
233{-# INLINE readInChunksOf #-}
234readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
235readInChunksOf chunkSize h = AS.concat $ readArraysOf chunkSize h
237-- TODO
238-- Generate a stream of elements of the given type from a file 'Handle'.
239-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
240--
241-- > read = 'readInChunksOf' A.defaultChunkSize
242-- | Generate a byte stream from a file 'Handle'.
243--
244-- @since 0.7.0
245{-# INLINE read #-}
246read :: (IsStream t, MonadIO m) => Handle -> t m Word8
247read = AS.concat . readArrays
249-------------------------------------------------------------------------------
250-- Writing
251-------------------------------------------------------------------------------
253-- | Write a stream of arrays to a handle.
254--
255-- @since 0.7.0
256{-# INLINE writeArrays #-}
257writeArrays :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
258writeArrays h = FL.drainBy (liftIO . writeArray h)
260-- | @writeArraysInChunksOf chunkSize handle@ writes a stream of arrays
261-- to @handle@ after coalescing the adjacent arrays in chunks of @chunkSize@.
262-- We never split an array, if a single array is bigger than the specified size
263-- it emitted as it is. Multiple arrays are coalesed as long as the total size
264-- remains below the specified size.
265--
266-- @since 0.7.0
267{-# INLINE writeArraysInChunksOf #-}
268writeArraysInChunksOf :: (MonadIO m, Storable a)
269 => Int -> Handle -> Fold m (Array a) ()
270writeArraysInChunksOf n h = lpackArraysChunksOf n (writeArrays h)
272-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
273--
274-- XXX test this
275-- Note that if you use a chunk size less than 8K (GHC's default buffer
276-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
277-- do not want buffering to occur at GHC level as well. Same thing applies to
278-- writes as well.
280-- | @writeInChunksOf chunkSize handle@ writes the input stream to @handle@ in
281-- chunks of @chunkSize@. A write is performed to the IO device as soon as we
282-- collect the required input size.
283--
284-- @since 0.7.0
285{-# INLINE writeInChunksOf #-}
286writeInChunksOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
287writeInChunksOf n h = FL.lchunksOf n (writeNUnsafe n) (writeArrays h)
289-- > write = 'writeInChunksOf' A.defaultChunkSize
290--
291-- | Write a byte stream to a file handle. Accumulates the input in chunks of
292-- up to 'A.defaultChunkSize' before writing.
293--
294-- @since 0.7.0
295{-# INLINE write #-}
296write :: MonadIO m => Handle -> Fold m Word8 ()
297write = writeInChunksOf defaultChunkSize
299{-
300{-# INLINE write #-}
301write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
302write = toHandleWith A.defaultChunkSize
303-}
305-- XXX mmap a file into an array. This could be useful for in-place operations
306-- on a file. For example, we can quicksort the contents of a file by mmapping
307-- it.
309-------------------------------------------------------------------------------
310-- IO with encoding/decoding Unicode characters
311-------------------------------------------------------------------------------
313{-
314-- |
315-- > readUtf8 = decodeUtf8 . read
316--
317-- Read a UTF8 encoded stream of unicode characters from a file handle.
318--
319-- @since 0.7.0
320{-# INLINE readUtf8 #-}
321readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
322readUtf8 = decodeUtf8 . read
324-- |
325-- > writeUtf8 h s = write h $ encodeUtf8 s
326--
327-- Encode a stream of unicode characters to UTF8 and write it to the given file
328-- handle. Default block buffering applies to the writes.
329--
330-- @since 0.7.0
331{-# INLINE writeUtf8 #-}
332writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
333writeUtf8 h s = write h $ encodeUtf8 s
335-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
336-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
337-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
338-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
339-- option.
340--
341-- @since 0.7.0
342{-# INLINE writeUtf8ByLines #-}
343writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
344writeUtf8ByLines = undefined
346-- | Read UTF-8 lines from a file handle and apply the specified fold to each
347-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
348--
349-- @since 0.7.0
350{-# INLINE readLines #-}
351readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
352readLines h f = foldLines (readUtf8 h) f
354-------------------------------------------------------------------------------
355-- Framing on a sequence
356-------------------------------------------------------------------------------
358-- | Read a stream from a file handle and split it into frames delimited by
359-- the specified sequence of elements. The supplied fold is applied on each
360-- frame.
361--
362-- @since 0.7.0
363{-# INLINE readFrames #-}
364readFrames :: (IsStream t, MonadIO m, Storable a)
365 => Array a -> Handle -> Fold m a b -> t m b
366readFrames = undefined -- foldFrames . read
368-- | Write a stream to the given file handle buffering up to frames separated
369-- by the given sequence or up to a maximum of @defaultChunkSize@.
370--
371-- @since 0.7.0
372{-# INLINE writeByFrames #-}
373writeByFrames :: (IsStream t, MonadIO m, Storable a)
374 => Array a -> Handle -> t m a -> m ()
375writeByFrames = undefined
377-------------------------------------------------------------------------------
378-- Framing by time
379-------------------------------------------------------------------------------
381-- | Write collecting the input in sessions of n seconds or if chunkSize
382-- gets exceeded.
383{-# INLINE writeByChunksOrSessionsOf #-}
384writeByChunksOrSessionsOf :: MonadIO m
385 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
386writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
388-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
389-- gets exceeded.
390{-# INLINE writeBySessionsOf #-}
391writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
392writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
394-------------------------------------------------------------------------------
395-- Random Access IO (Seek)
396-------------------------------------------------------------------------------
398-- XXX handles could be shared, so we may not want to use the handle state at
399-- all for these APIs. we can use pread and pwrite instead. On windows we will
400-- need to use readFile/writeFile with an offset argument.
402-------------------------------------------------------------------------------
404-- | Read the element at the given index treating the file as an array.
405--
406-- @since 0.7.0
407{-# INLINE readIndex #-}
408readIndex :: Storable a => Handle -> Int -> Maybe a
409readIndex arr i = undefined
411-- NOTE: To represent a range to read we have chosen (start, size) instead of
412-- (start, end). This helps in removing the ambiguity of whether "end" is
413-- included in the range or not.
414--
415-- We could avoid specifying the range to be read and instead use "take size"
416-- on the stream, but it may end up reading more and then consume it partially.
418-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
419-- from @handle@ starting at the offset @pos@ from the beginning of the file.
420--
421-- Reads are performed in chunks of size @chunkSize@. For block devices, to
422-- avoid reading partial blocks @chunkSize@ must align with the block size of
423-- the underlying device. If the underlying block size is unknown, it is a good
424-- idea to keep it a multiple 4KiB. This API ensures that the start of each
425-- chunk is aligned with @chunkSize@ from second chunk onwards.
426--
427{-# INLINE readSliceWith #-}
428readSliceWith :: (IsStream t, MonadIO m, Storable a)
429 => Int -> Handle -> Int -> Int -> t m a
430readSliceWith chunkSize h pos len = undefined
432-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
433-- at index @i@ and reading up to @count@ elements in the forward direction
434-- ending at the index @i + count - 1@.
435--
436-- @since 0.7.0
437{-# INLINE readSlice #-}
438readSlice :: (IsStream t, MonadIO m, Storable a)
439 => Handle -> Int -> Int -> t m a
440readSlice = readSliceWith A.defaultChunkSize
442-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
443-- at index @i@ and reading up to @count@ elements in the reverse direction
444-- ending at the index @i - count + 1@.
445--
446-- @since 0.7.0
447{-# INLINE readSliceRev #-}
448readSliceRev :: (IsStream t, MonadIO m, Storable a)
449 => Handle -> Int -> Int -> t m a
450readSliceRev h i count = undefined
452-- | Write the given element at the given index in the file.
453--
454-- @since 0.7.0
455{-# INLINE writeIndex #-}
456writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
457writeIndex h i a = undefined
459-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
460-- starting at index @i@ and writing up to @count@ elements in the forward
461-- direction ending at the index @i + count - 1@.
462--
463-- @since 0.7.0
464{-# INLINE writeSlice #-}
465writeSlice :: (IsStream t, Monad m, Storable a)
466 => Handle -> Int -> Int -> t m a -> m ()
467writeSlice h i len s = undefined
469-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
470-- starting at index @i@ and writing up to @count@ elements in the reverse
471-- direction ending at the index @i - count + 1@.
472--
473-- @since 0.7.0
474{-# INLINE writeSliceRev #-}
475writeSliceRev :: (IsStream t, Monad m, Storable a)
476 => Handle -> Int -> Int -> t m a -> m ()
477writeSliceRev arr i len s = undefined
478-}