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
58 , readChunksFromToWith
88import Control.Monad.Catch (MonadCatch)
89import Control.Monad.IO.Class (MonadIO(..))
90import Data.Word (Word8)
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.Control.Concurrent (MonadAsync)
98import Streamly.Internal.Data.Fold.Type (Fold(..))
99import Streamly.Internal.Data.Unfold.Type (Unfold(..))
100import Streamly.Internal.Data.Array.Foreign.Type (Array(..), writeNUnsafe)
101import Streamly.Internal.Data.Stream.Serial (SerialT)
102import Streamly.Internal.Data.Stream.IsStream.Type (IsStream)
103-- import Streamly.Data.Fold (Fold)
104-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
105import Streamly.Internal.System.IO (defaultChunkSize)
107import qualified Streamly.Internal.Data.Array.Foreign as A
108import qualified Streamly.Internal.Data.Fold.Type as FL
109import qualified Streamly.Internal.Data.Unfold as UF
110import qualified Streamly.Internal.FileSystem.Handle as FH
111import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
112import qualified Streamly.Internal.Data.Stream.IsStream as S
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{-# INLINE usingFile #-}
154usingFile :: (MonadCatch m, MonadAsync m)
155 => Unfold m Handle a -> Unfold m FilePath a
157 UF.bracket (\file -> liftIO $ openFile file ReadMode)
160{-# INLINE 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{-# INLINE usingFile3 #-}
174usingFile3 :: (MonadCatch m, MonadAsync m)
175 => Unfold m (x, y, z, Handle) a -> Unfold m (x, y, z, FilePath) a
176usingFile3 = UF.bracket before after
180 before (x, y, z, file) = do
181 h <- liftIO $ openFile file ReadMode
184 after (_, _, _, h) = liftIO $ hClose h
186-------------------------------------------------------------------------------
188-------------------------------------------------------------------------------
192-------------------------------------------------------------------------------
194-------------------------------------------------------------------------------
196-- | Write an array to a file. Overwrites the file if it exists.
199{-# INLINABLE putChunk #-}
200putChunk :: FilePath -> Array a -> IO ()
201putChunk file arr = SIO.withFile file WriteMode (`FH.putChunk` arr)
203-- | append an array to a file.
206{-# INLINABLE appendArray #-}
207appendArray :: FilePath -> Array a -> IO ()
208appendArray file arr = SIO.withFile file AppendMode (`FH.putChunk` arr)
210-------------------------------------------------------------------------------
211-- Stream of Arrays IO
212-------------------------------------------------------------------------------
214-- | @toChunksWith size file@ reads a stream of arrays from file @file@.
215-- The maximum size of a single array is specified by @size@. The actual size
216-- read may be less than or equal to @size@.
219{-# INLINE toChunksWith #-}
220toChunksWith :: (IsStream t, MonadCatch m, MonadAsync m)
221 => Int -> FilePath -> t m (Array Word8)
222toChunksWith size file =
223 withFile file ReadMode (FH.getChunksWith size)
225-- XXX read 'Array a' instead of Word8
227-- | @toChunks file@ reads a stream of arrays from file @file@.
228-- The maximum size of a single array is limited to @defaultChunkSize@. The
229-- actual size read may be less than @defaultChunkSize@.
231-- > toChunks = toChunksWith defaultChunkSize
234{-# INLINE toChunks #-}
235toChunks :: (IsStream t, MonadCatch m, MonadAsync m)
236 => FilePath -> t m (Array Word8)
237toChunks = toChunksWith defaultChunkSize
239-------------------------------------------------------------------------------
240-- Read File to Stream
241-------------------------------------------------------------------------------
243-- TODO for concurrent streams implement readahead IO. We can send multiple
244-- read requests at the same time. For serial case we can use async IO. We can
245-- also control the read throughput in mbps or IOPS.
247-- | Unfold the tuple @(bufsize, filepath)@ into a stream of 'Word8' arrays.
248-- Read requests to the IO device are performed using a buffer of size
249-- @bufsize@. The size of an array in the resulting stream is always less than
250-- or equal to @bufsize@.
254{-# INLINE readChunksWith #-}
255readChunksWith :: (MonadCatch m, MonadAsync m)
256 => Unfold m (Int, FilePath) (Array Word8)
257readChunksWith = usingFile2 FH.readChunksWith
259-- | Unfold the tuple @(from, to, bufsize, filepath)@ into a stream
261-- Read requests to the IO device are performed using a buffer of size
262-- @bufsize@ starting from absolute offset of @from@ till the absolute
263-- position of @to@. The size of an array in the resulting stream is always
264-- less than or equal to @bufsize@.
267{-# INLINE readChunksFromToWith #-}
268readChunksFromToWith :: (MonadCatch m, MonadAsync m) =>
269 Unfold m (Int, Int, Int, FilePath) (Array Word8)
270readChunksFromToWith = usingFile3 FH.readChunksFromToWith
272-- | Unfolds a 'FilePath' into a stream of 'Word8' arrays. Requests to the IO
273-- device are performed using a buffer of size
274-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'. The
275-- size of arrays in the resulting stream are therefore less than or equal to
276-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
279{-# INLINE readChunks #-}
280readChunks :: (MonadCatch m, MonadAsync m) => Unfold m FilePath (Array Word8)
281readChunks = usingFile FH.readChunks
283-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
284-- to the IO device are performed using buffers of @bufsize@.
287{-# INLINE readWith #-}
288readWith :: (MonadCatch m, MonadAsync m) => Unfold m (Int, FilePath) Word8
289readWith = usingFile2 FH.readWith
291-- | Unfolds a file path into a byte stream. IO requests to the device are
292-- performed in sizes of
293-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
297read :: (MonadCatch m, MonadAsync m) => Unfold m FilePath Word8
298read = UF.many A.read (usingFile FH.readChunks)
300-- | Generate a stream of bytes from a file specified by path. The stream ends
301-- when EOF is encountered. File is locked using multiple reader and single
302-- writer locking mode.
306{-# INLINE toBytes #-}
307toBytes :: (IsStream t, MonadCatch m, MonadAsync m) => FilePath -> t m Word8
308toBytes file = AS.concat $ withFile file ReadMode FH.getChunks
311-- | Generate a stream of elements of the given type from a file 'Handle'. The
312-- stream ends when EOF is encountered. File is not locked for exclusive reads,
313-- writers can keep writing to the file.
316{-# INLINE readShared #-}
317readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
318readShared = undefined
321-------------------------------------------------------------------------------
323-------------------------------------------------------------------------------
325{-# INLINE fromChunksMode #-}
326fromChunksMode :: (MonadAsync m, MonadCatch m)
327 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
328fromChunksMode mode file xs = S.drain $
329 withFile file mode (\h -> S.mapM (FH.putChunk h) xs)
331-- | Write a stream of arrays to a file. Overwrites the file if it exists.
334{-# INLINE fromChunks #-}
335fromChunks :: (MonadAsync m, MonadCatch m)
336 => FilePath -> SerialT m (Array a) -> m ()
337fromChunks = fromChunksMode WriteMode
339-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
342-- Note that if you use a chunk size less than 8K (GHC's default buffer
343-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
344-- do not want buffering to occur at GHC level as well. Same thing applies to
347-- | Like 'write' but provides control over the write buffer. Output will
348-- be written to the IO device as soon as we collect the specified number of
352{-# INLINE fromBytesWith #-}
353fromBytesWith :: (MonadAsync m, MonadCatch m)
354 => Int -> FilePath -> SerialT m Word8 -> m ()
355fromBytesWith n file xs = fromChunks file $ AS.arraysOf n xs
357-- > write = 'writeWith' defaultChunkSize
359-- | Write a byte stream to a file. Combines the bytes in chunks of size
360-- up to 'A.defaultChunkSize' before writing. If the file exists it is
361-- truncated to zero size before writing. If the file does not exist it is
362-- created. File is locked using single writer locking mode.
365{-# INLINE fromBytes #-}
366fromBytes :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
367fromBytes = fromBytesWith defaultChunkSize
371write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
372write = toHandleWith A.defaultChunkSize
375-- | Write a stream of chunks to a handle. Each chunk in the stream is written
376-- to the device as a separate IO request.
379{-# INLINE writeChunks #-}
380writeChunks :: (MonadIO m, MonadCatch m)
381 => FilePath -> Fold m (Array a) ()
382writeChunks path = Fold step initial extract
385 h <- liftIO (openFile path WriteMode)
386 fld <- FL.initialize (FH.writeChunks h)
387 `MC.onException` liftIO (hClose h)
388 return $ FL.Partial (fld, h)
390 r <- FL.snoc fld x `MC.onException` liftIO (hClose h)
391 return $ FL.Partial (r, h)
392 extract (Fold _ initial1 extract1, h) = do
396 FL.Partial fs -> extract1 fs
397 FL.Done fb -> return fb
399-- | @writeWith chunkSize handle@ writes the input stream to @handle@.
400-- Bytes in the input stream are collected into a buffer until we have a chunk
401-- of size @chunkSize@ and then written to the IO device.
404{-# INLINE writeWith #-}
405writeWith :: (MonadIO m, MonadCatch m)
406 => Int -> FilePath -> Fold m Word8 ()
408 FL.chunksOf n (writeNUnsafe n) (writeChunks path)
410-- > write = 'writeWith' A.defaultChunkSize
412-- | Write a byte stream to a file. Accumulates the input in chunks of up to
413-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize' before writing to
419write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
420write = writeWith defaultChunkSize
422-- | Append a stream of arrays to a file.
425{-# INLINE appendChunks #-}
426appendChunks :: (MonadAsync m, MonadCatch m)
427 => FilePath -> SerialT m (Array a) -> m ()
428appendChunks = fromChunksMode AppendMode
430-- | Like 'append' but provides control over the write buffer. Output will
431-- be written to the IO device as soon as we collect the specified number of
435{-# INLINE appendWith #-}
436appendWith :: (MonadAsync m, MonadCatch m)
437 => Int -> FilePath -> SerialT m Word8 -> m ()
438appendWith n file xs = appendChunks file $ AS.arraysOf n xs
440-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
441-- 'A.defaultChunkSize' before writing. If the file exists then the new data
442-- is appended to the file. If the file does not exist it is created. File is
443-- locked using single writer locking mode.
447append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
448append = appendWith defaultChunkSize
451-- | Like 'append' but the file is not locked for exclusive writes.
454{-# INLINE appendShared #-}
455appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
456appendShared = undefined
459-------------------------------------------------------------------------------
460-- IO with encoding/decoding Unicode characters
461-------------------------------------------------------------------------------
465-- > readUtf8 = decodeUtf8 . read
467-- Read a UTF8 encoded stream of unicode characters from a file handle.
470{-# INLINE readUtf8 #-}
471readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
472readUtf8 = decodeUtf8 . read
475-- > writeUtf8 h s = write h $ encodeUtf8 s
477-- Encode a stream of unicode characters to UTF8 and write it to the given file
478-- handle. Default block buffering applies to the writes.
481{-# INLINE writeUtf8 #-}
482writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
483writeUtf8 h s = write h $ encodeUtf8 s
485-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
486-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
487-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
488-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
492{-# INLINE writeUtf8ByLines #-}
493writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
494writeUtf8ByLines = undefined
496-- | Read UTF-8 lines from a file handle and apply the specified fold to each
497-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
500{-# INLINE readLines #-}
501readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
502readLines h f = foldLines (readUtf8 h) f
504-------------------------------------------------------------------------------
505-- Framing on a sequence
506-------------------------------------------------------------------------------
508-- | Read a stream from a file handle and split it into frames delimited by
509-- the specified sequence of elements. The supplied fold is applied on each
513{-# INLINE readFrames #-}
514readFrames :: (IsStream t, MonadIO m, Storable a)
515 => Array a -> Handle -> Fold m a b -> t m b
516readFrames = undefined -- foldFrames . read
518-- | Write a stream to the given file handle buffering up to frames separated
519-- by the given sequence or up to a maximum of @defaultChunkSize@.
522{-# INLINE writeByFrames #-}
523writeByFrames :: (IsStream t, MonadIO m, Storable a)
524 => Array a -> Handle -> t m a -> m ()
525writeByFrames = undefined
527-------------------------------------------------------------------------------
528-- Random Access IO (Seek)
529-------------------------------------------------------------------------------
531-- XXX handles could be shared, so we may not want to use the handle state at
532-- all for these APIs. we can use pread and pwrite instead. On windows we will
533-- need to use readFile/writeFile with an offset argument.
535-------------------------------------------------------------------------------
537-- | Read the element at the given index treating the file as an array.
540{-# INLINE readIndex #-}
541readIndex :: Storable a => Handle -> Int -> Maybe a
542readIndex arr i = undefined
544-- NOTE: To represent a range to read we have chosen (start, size) instead of
545-- (start, end). This helps in removing the ambiguity of whether "end" is
546-- included in the range or not.
548-- We could avoid specifying the range to be read and instead use "take size"
549-- on the stream, but it may end up reading more and then consume it partially.
551-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
552-- from @handle@ starting at the offset @pos@ from the beginning of the file.
554-- Reads are performed in chunks of size @chunkSize@. For block devices, to
555-- avoid reading partial blocks @chunkSize@ must align with the block size of
556-- the underlying device. If the underlying block size is unknown, it is a good
557-- idea to keep it a multiple 4KiB. This API ensures that the start of each
558-- chunk is aligned with @chunkSize@ from second chunk onwards.
560{-# INLINE readSliceWith #-}
561readSliceWith :: (IsStream t, MonadIO m, Storable a)
562 => Int -> Handle -> Int -> Int -> t m a
563readSliceWith chunkSize h pos len = undefined
565-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
566-- at index @i@ and reading up to @count@ elements in the forward direction
567-- ending at the index @i + count - 1@.
570{-# INLINE readSlice #-}
571readSlice :: (IsStream t, MonadIO m, Storable a)
572 => Handle -> Int -> Int -> t m a
573readSlice = readSliceWith defaultChunkSize
575-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
576-- at index @i@ and reading up to @count@ elements in the reverse direction
577-- ending at the index @i - count + 1@.
580{-# INLINE readSliceRev #-}
581readSliceRev :: (IsStream t, MonadIO m, Storable a)
582 => Handle -> Int -> Int -> t m a
583readSliceRev h i count = undefined
585-- | Write the given element at the given index in the file.
588{-# INLINE writeIndex #-}
589writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
590writeIndex h i a = undefined
592-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
593-- starting at index @i@ and writing up to @count@ elements in the forward
594-- direction ending at the index @i + count - 1@.
597{-# INLINE writeSlice #-}
598writeSlice :: (IsStream t, Monad m, Storable a)
599 => Handle -> Int -> Int -> t m a -> m ()
600writeSlice h i len s = undefined
602-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
603-- starting at index @i@ and writing up to @count@ elements in the reverse
604-- direction ending at the index @i - count + 1@.
607{-# INLINE writeSliceRev #-}
608writeSliceRev :: (IsStream t, Monad m, Storable a)
609 => Handle -> Int -> Int -> t m a -> m ()
610writeSliceRev 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