4-- Module : Streamly.Internal.FileSystem.File
5-- Copyright : (c) 2019 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : pre-release
12-- Read and write streams and arrays to and from files specified by their paths
13-- in the file system. Unlike the handle based APIs which can have a read/write
14-- session consisting of multiple reads and writes to the handle, these APIs
15-- are one shot read or write APIs. These APIs open the file handle, perform
16-- the requested operation and close the handle. Thease are safer compared to
17-- the handle based APIs as there is no possibility of a file descriptor
20-- > import qualified Streamly.Internal.FileSystem.File as File
23module Streamly.Internal.FileSystem.File
26 -- | Stream data to or from a file or device sequentially. When reading,
27 -- the stream is lazy and generated on-demand as the consumer consumes it.
28 -- Read IO requests to the IO device are performed in chunks limited to a
29 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
30 -- documentation. One IO request may or may not read the full
31 -- chunk. If the whole stream is not consumed, it is possible that we may
32 -- read slightly more from the IO device than what the consumer needed.
33 -- Unless specified otherwise in the API, writes are collected into chunks
34 -- of @defaultChunkSize@ before they are written to the IO device.
36 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
37 -- including disks, files, memory devices, terminals, pipes, sockets and
38 -- fifos. While random access APIs work only for files or devices that have
39 -- random access or seek capability for example disks, memory devices.
40 -- Devices like terminals, pipes, sockets and fifos do not have random
43 -- ** File IO Using Handle
57 , readChunksWithBufferOf
60 , toChunksWithBufferOf
71 , fromBytesWithBufferOf
87import Control.Monad.Catch (MonadCatch)
88import Control.Monad.IO.Class (MonadIO(..))
89import Data.Word (Word8)
90import Foreign.Storable (Storable(..))
91import System.IO (Handle, openFile, IOMode(..), hClose)
92import Prelude hiding (read)
94import qualified Control.Monad.Catch as MC
95import qualified System.IO as SIO
97import Streamly.Internal.Data.Fold.Type (Fold(..))
98import Streamly.Internal.Data.Unfold.Type (Unfold(..))
99import Streamly.Internal.Data.Array.Foreign.Type (Array(..), writeNUnsafe)
100import Streamly.Internal.Data.Stream.Serial (SerialT)
101import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
102import Streamly.Internal.Data.SVar (MonadAsync)
103-- import Streamly.Data.Fold (Fold)
104-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
105import Streamly.Internal.System.IO (defaultChunkSize)
107import qualified Streamly.Internal.Data.Fold.Type as FL
108import qualified Streamly.Internal.Data.Unfold as UF
109import qualified Streamly.Internal.FileSystem.Handle as FH
110import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
111import qualified Streamly.Internal.Data.Stream.IsStream as S
112import qualified Streamly.Data.Array.Foreign as A
114-------------------------------------------------------------------------------
116-------------------------------------------------------------------------------
118-- The following references may be useful to build an understanding about the
121-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
122-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
123-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
124-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
125-- https://www.w3.org/TR/FileAPI/ for http file API.
127-------------------------------------------------------------------------------
129-------------------------------------------------------------------------------
131-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
132-- the resulting handle to the computation @act@. The handle will be
133-- closed on exit from 'withFile', whether by normal termination or by
134-- raising an exception. If closing the handle raises an exception, then
135-- this exception will be raised by 'withFile' rather than any exception
140{-# INLINE withFile #-}
141withFile :: (IsStream t, MonadCatch m, MonadAsync m)
142 => FilePath -> IOMode -> (Handle -> t m a) -> t m a
143withFile file mode = S.bracket (liftIO $ openFile file mode) (liftIO . hClose)
145-- | Transform an 'Unfold' from a 'Handle' to an unfold from a 'FilePath'. The
146-- resulting unfold opens a handle in 'ReadMode', uses it using the supplied
147-- unfold and then makes sure that the handle is closed on normal termination
148-- or in case of an exception. If closing the handle raises an exception, then
149-- this exception will be raised by 'usingFile'.
153{-# INLINABLE usingFile #-}
154usingFile :: (MonadCatch m, MonadAsync m)
155 => Unfold m Handle a -> Unfold m FilePath a
157 UF.bracket (\file -> liftIO $ openFile file ReadMode)
160{-# INLINABLE usingFile2 #-}
161usingFile2 :: (MonadCatch m, MonadAsync m)
162 => Unfold m (x, Handle) a -> Unfold m (x, FilePath) a
163usingFile2 = UF.bracket before after
167 before (x, file) = do
168 h <- liftIO $ openFile file ReadMode
171 after (_, h) = liftIO $ hClose h
173-------------------------------------------------------------------------------
175-------------------------------------------------------------------------------
179-------------------------------------------------------------------------------
181-------------------------------------------------------------------------------
183-- | Write an array to a file. Overwrites the file if it exists.
186{-# INLINABLE putChunk #-}
187putChunk :: Storable a => FilePath -> Array a -> IO ()
188putChunk file arr = SIO.withFile file WriteMode (`FH.putChunk` arr)
190-- | append an array to a file.
193{-# INLINABLE appendArray #-}
194appendArray :: Storable a => FilePath -> Array a -> IO ()
195appendArray file arr = SIO.withFile file AppendMode (`FH.putChunk` arr)
197-------------------------------------------------------------------------------
198-- Stream of Arrays IO
199-------------------------------------------------------------------------------
201-- | @toChunksWithBufferOf size file@ reads a stream of arrays from file @file@.
202-- The maximum size of a single array is specified by @size@. The actual size
203-- read may be less than or equal to @size@.
204{-# INLINABLE toChunksWithBufferOf #-}
205toChunksWithBufferOf :: (IsStream t, MonadCatch m, MonadAsync m)
206 => Int -> FilePath -> t m (Array Word8)
207toChunksWithBufferOf size file =
208 withFile file ReadMode (FH.toChunksWithBufferOf size)
210-- XXX read 'Array a' instead of Word8
212-- | @toChunks file@ reads a stream of arrays from file @file@.
213-- The maximum size of a single array is limited to @defaultChunkSize@. The
214-- actual size read may be less than @defaultChunkSize@.
216-- > toChunks = toChunksWithBufferOf defaultChunkSize
219{-# INLINE toChunks #-}
220toChunks :: (IsStream t, MonadCatch m, MonadAsync m)
221 => FilePath -> t m (Array Word8)
222toChunks = toChunksWithBufferOf defaultChunkSize
224-------------------------------------------------------------------------------
225-- Read File to Stream
226-------------------------------------------------------------------------------
228-- TODO for concurrent streams implement readahead IO. We can send multiple
229-- read requests at the same time. For serial case we can use async IO. We can
230-- also control the read throughput in mbps or IOPS.
232-- | Unfold the tuple @(bufsize, filepath)@ into a stream of 'Word8' arrays.
233-- Read requests to the IO device are performed using a buffer of size
234-- @bufsize@. The size of an array in the resulting stream is always less than
235-- or equal to @bufsize@.
239{-# INLINE readChunksWithBufferOf #-}
240readChunksWithBufferOf :: (MonadCatch m, MonadAsync m)
241 => Unfold m (Int, FilePath) (Array Word8)
242readChunksWithBufferOf = usingFile2 FH.readChunksWithBufferOf
244-- | Unfolds a 'FilePath' into a stream of 'Word8' arrays. Requests to the IO
245-- device are performed using a buffer of size
246-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'. The
247-- size of arrays in the resulting stream are therefore less than or equal to
248-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
251{-# INLINE readChunks #-}
252readChunks :: (MonadCatch m, MonadAsync m) => Unfold m FilePath (Array Word8)
253readChunks = usingFile FH.readChunks
255-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
256-- to the IO device are performed using buffers of @bufsize@.
259{-# INLINE readWithBufferOf #-}
260readWithBufferOf :: (MonadCatch m, MonadAsync m) => Unfold m (Int, FilePath) Word8
261readWithBufferOf = usingFile2 FH.readWithBufferOf
263-- | Unfolds a file path into a byte stream. IO requests to the device are
264-- performed in sizes of
265-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
269read :: (MonadCatch m, MonadAsync m) => Unfold m FilePath Word8
270read = UF.many (usingFile FH.readChunks) A.read
272-- | Generate a stream of bytes from a file specified by path. The stream ends
273-- when EOF is encountered. File is locked using multiple reader and single
274-- writer locking mode.
278{-# INLINE toBytes #-}
279toBytes :: (IsStream t, MonadCatch m, MonadAsync m) => FilePath -> t m Word8
280toBytes file = AS.concat $ withFile file ReadMode FH.toChunks
283-- | Generate a stream of elements of the given type from a file 'Handle'. The
284-- stream ends when EOF is encountered. File is not locked for exclusive reads,
285-- writers can keep writing to the file.
288{-# INLINE readShared #-}
289readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
290readShared = undefined
293-------------------------------------------------------------------------------
295-------------------------------------------------------------------------------
297{-# INLINE fromChunksMode #-}
298fromChunksMode :: (MonadAsync m, MonadCatch m, Storable a)
299 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
300fromChunksMode mode file xs = S.drain $
301 withFile file mode (\h -> S.mapM (FH.putChunk h) xs)
303-- | Write a stream of arrays to a file. Overwrites the file if it exists.
306{-# INLINE fromChunks #-}
307fromChunks :: (MonadAsync m, MonadCatch m, Storable a)
308 => FilePath -> SerialT m (Array a) -> m ()
309fromChunks = fromChunksMode WriteMode
311-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
314-- Note that if you use a chunk size less than 8K (GHC's default buffer
315-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
316-- do not want buffering to occur at GHC level as well. Same thing applies to
319-- | Like 'write' but provides control over the write buffer. Output will
320-- be written to the IO device as soon as we collect the specified number of
324{-# INLINE fromBytesWithBufferOf #-}
325fromBytesWithBufferOf :: (MonadAsync m, MonadCatch m)
326 => Int -> FilePath -> SerialT m Word8 -> m ()
327fromBytesWithBufferOf n file xs = fromChunks file $ AS.arraysOf n xs
329-- > write = 'writeWithBufferOf' defaultChunkSize
331-- | Write a byte stream to a file. Combines the bytes in chunks of size
332-- up to 'A.defaultChunkSize' before writing. If the file exists it is
333-- truncated to zero size before writing. If the file does not exist it is
334-- created. File is locked using single writer locking mode.
337{-# INLINE fromBytes #-}
338fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
339fromBytes = fromBytesWithBufferOf defaultChunkSize
343write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
344write = toHandleWith A.defaultChunkSize
347-- | Write a stream of chunks to a handle. Each chunk in the stream is written
348-- to the device as a separate IO request.
351{-# INLINE writeChunks #-}
352writeChunks :: (MonadIO m, MonadCatch m, Storable a)
353 => FilePath -> Fold m (Array a) ()
354writeChunks path = Fold step initial extract
357 h <- liftIO (openFile path WriteMode)
358 fld <- FL.initialize (FH.writeChunks h)
359 `MC.onException` liftIO (hClose h)
360 return $ FL.Partial (fld, h)
362 r <- FL.runStep fld x `MC.onException` liftIO (hClose h)
363 return $ FL.Partial (r, h)
364 extract (Fold _ initial1 extract1, h) = do
368 FL.Partial fs -> extract1 fs
369 FL.Done fb -> return fb
371-- | @writeWithBufferOf chunkSize handle@ writes the input stream to @handle@.
372-- Bytes in the input stream are collected into a buffer until we have a chunk
373-- of size @chunkSize@ and then written to the IO device.
376{-# INLINE writeWithBufferOf #-}
377writeWithBufferOf :: (MonadIO m, MonadCatch m)
378 => Int -> FilePath -> Fold m Word8 ()
379writeWithBufferOf n path =
380 FL.chunksOf n (writeNUnsafe n) (writeChunks path)
382-- > write = 'writeWithBufferOf' A.defaultChunkSize
384-- | Write a byte stream to a file. Accumulates the input in chunks of up to
385-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize' before writing to
391write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
392write = writeWithBufferOf defaultChunkSize
394-- | Append a stream of arrays to a file.
397{-# INLINE appendChunks #-}
398appendChunks :: (MonadAsync m, MonadCatch m, Storable a)
399 => FilePath -> SerialT m (Array a) -> m ()
400appendChunks = fromChunksMode AppendMode
402-- | Like 'append' but provides control over the write buffer. Output will
403-- be written to the IO device as soon as we collect the specified number of
407{-# INLINE appendWithBufferOf #-}
408appendWithBufferOf :: (MonadAsync m, MonadCatch m)
409 => Int -> FilePath -> SerialT m Word8 -> m ()
410appendWithBufferOf n file xs = appendChunks file $ AS.arraysOf n xs
412-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
413-- 'A.defaultChunkSize' before writing. If the file exists then the new data
414-- is appended to the file. If the file does not exist it is created. File is
415-- locked using single writer locking mode.
419append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
420append = appendWithBufferOf defaultChunkSize
423-- | Like 'append' but the file is not locked for exclusive writes.
426{-# INLINE appendShared #-}
427appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
428appendShared = undefined
431-------------------------------------------------------------------------------
432-- IO with encoding/decoding Unicode characters
433-------------------------------------------------------------------------------
437-- > readUtf8 = decodeUtf8 . read
439-- Read a UTF8 encoded stream of unicode characters from a file handle.
442{-# INLINE readUtf8 #-}
443readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
444readUtf8 = decodeUtf8 . read
447-- > writeUtf8 h s = write h $ encodeUtf8 s
449-- Encode a stream of unicode characters to UTF8 and write it to the given file
450-- handle. Default block buffering applies to the writes.
453{-# INLINE writeUtf8 #-}
454writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
455writeUtf8 h s = write h $ encodeUtf8 s
457-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
458-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
459-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
460-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
464{-# INLINE writeUtf8ByLines #-}
465writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
466writeUtf8ByLines = undefined
468-- | Read UTF-8 lines from a file handle and apply the specified fold to each
469-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
472{-# INLINE readLines #-}
473readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
474readLines h f = foldLines (readUtf8 h) f
476-------------------------------------------------------------------------------
477-- Framing on a sequence
478-------------------------------------------------------------------------------
480-- | Read a stream from a file handle and split it into frames delimited by
481-- the specified sequence of elements. The supplied fold is applied on each
485{-# INLINE readFrames #-}
486readFrames :: (IsStream t, MonadIO m, Storable a)
487 => Array a -> Handle -> Fold m a b -> t m b
488readFrames = undefined -- foldFrames . read
490-- | Write a stream to the given file handle buffering up to frames separated
491-- by the given sequence or up to a maximum of @defaultChunkSize@.
494{-# INLINE writeByFrames #-}
495writeByFrames :: (IsStream t, MonadIO m, Storable a)
496 => Array a -> Handle -> t m a -> m ()
497writeByFrames = undefined
499-------------------------------------------------------------------------------
500-- Random Access IO (Seek)
501-------------------------------------------------------------------------------
503-- XXX handles could be shared, so we may not want to use the handle state at
504-- all for these APIs. we can use pread and pwrite instead. On windows we will
505-- need to use readFile/writeFile with an offset argument.
507-------------------------------------------------------------------------------
509-- | Read the element at the given index treating the file as an array.
512{-# INLINE readIndex #-}
513readIndex :: Storable a => Handle -> Int -> Maybe a
514readIndex arr i = undefined
516-- NOTE: To represent a range to read we have chosen (start, size) instead of
517-- (start, end). This helps in removing the ambiguity of whether "end" is
518-- included in the range or not.
520-- We could avoid specifying the range to be read and instead use "take size"
521-- on the stream, but it may end up reading more and then consume it partially.
523-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
524-- from @handle@ starting at the offset @pos@ from the beginning of the file.
526-- Reads are performed in chunks of size @chunkSize@. For block devices, to
527-- avoid reading partial blocks @chunkSize@ must align with the block size of
528-- the underlying device. If the underlying block size is unknown, it is a good
529-- idea to keep it a multiple 4KiB. This API ensures that the start of each
530-- chunk is aligned with @chunkSize@ from second chunk onwards.
532{-# INLINE readSliceWith #-}
533readSliceWith :: (IsStream t, MonadIO m, Storable a)
534 => Int -> Handle -> Int -> Int -> t m a
535readSliceWith chunkSize h pos len = undefined
537-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
538-- at index @i@ and reading up to @count@ elements in the forward direction
539-- ending at the index @i + count - 1@.
542{-# INLINE readSlice #-}
543readSlice :: (IsStream t, MonadIO m, Storable a)
544 => Handle -> Int -> Int -> t m a
545readSlice = readSliceWith defaultChunkSize
547-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
548-- at index @i@ and reading up to @count@ elements in the reverse direction
549-- ending at the index @i - count + 1@.
552{-# INLINE readSliceRev #-}
553readSliceRev :: (IsStream t, MonadIO m, Storable a)
554 => Handle -> Int -> Int -> t m a
555readSliceRev h i count = undefined
557-- | Write the given element at the given index in the file.
560{-# INLINE writeIndex #-}
561writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
562writeIndex h i a = undefined
564-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
565-- starting at index @i@ and writing up to @count@ elements in the forward
566-- direction ending at the index @i + count - 1@.
569{-# INLINE writeSlice #-}
570writeSlice :: (IsStream t, Monad m, Storable a)
571 => Handle -> Int -> Int -> t m a -> m ()
572writeSlice h i len s = undefined
574-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
575-- starting at index @i@ and writing up to @count@ elements in the reverse
576-- direction ending at the index @i - count + 1@.
579{-# INLINE writeSliceRev #-}
580writeSliceRev :: (IsStream t, Monad m, Storable a)
581 => Handle -> Int -> Int -> t m a -> m ()
582writeSliceRev arr i len s = undefined
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list