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
59 , chunkReaderFromToWith
63 , putChunk -- writeChunk?
74 , fromBytes -- putBytes?
87 , readChunksWithBufferOf
88 , readChunksFromToWith
91 , toChunksWithBufferOf
93 , fromBytesWithBufferOf
97import Control.Monad.Catch (MonadCatch)
98import Control.Monad.IO.Class (MonadIO(..))
99import Data.Word (Word8)
100import System.IO (Handle, openFile, IOMode(..), hClose)
101import Prelude hiding (read)
103import qualified Control.Monad.Catch as MC
104import qualified System.IO as SIO
106import Streamly.Data.Fold (chunksOf, drain)
107import Streamly.Internal.Data.Array.Type (Array(..), writeNUnsafe)
108import Streamly.Internal.Data.Fold.Type (Fold(..))
109import Streamly.Data.Stream (Stream)
110import Streamly.Internal.Data.Unfold.Type (Unfold(..))
111-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
112import Streamly.Internal.System.IO (defaultChunkSize)
114import qualified Streamly.Data.Array as A
115import qualified Streamly.Data.Unfold as UF
116import qualified Streamly.Internal.Data.Unfold as UF (bracketIO)
117import qualified Streamly.Internal.Data.Fold.Type as FL
118 (Step(..), snoc, reduce)
119import qualified Streamly.Internal.FileSystem.Handle as FH
120import qualified Streamly.Internal.Data.Stream.Chunked as AS
121import qualified Streamly.Data.Stream as S (fold, bracketIO, mapM)
123-------------------------------------------------------------------------------
125-------------------------------------------------------------------------------
127-- The following references may be useful to build an understanding about the
130-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
131-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
132-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
133-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
134-- https://www.w3.org/TR/FileAPI/ for http file API.
136-------------------------------------------------------------------------------
138-------------------------------------------------------------------------------
140-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
141-- the resulting handle to the computation @act@. The handle will be
142-- closed on exit from 'withFile', whether by normal termination or by
143-- raising an exception. If closing the handle raises an exception, then
144-- this exception will be raised by 'withFile' rather than any exception
149{-# INLINE withFile #-}
150withFile :: (MonadIO m, MonadCatch m)
151 => FilePath -> IOMode -> (Handle -> Stream m a) -> Stream m a
152withFile file mode = S.bracketIO (openFile file mode) hClose
154-- | Transform an 'Unfold' from a 'Handle' to an unfold from a 'FilePath'. The
155-- resulting unfold opens a handle in 'ReadMode', uses it using the supplied
156-- unfold and then makes sure that the handle is closed on normal termination
157-- or in case of an exception. If closing the handle raises an exception, then
158-- this exception will be raised by 'usingFile'.
162{-# INLINE usingFile #-}
163usingFile :: (MonadIO m, MonadCatch m)
164 => Unfold m Handle a -> Unfold m FilePath a
165usingFile = UF.bracketIO (`openFile` ReadMode) hClose
167{-# INLINE usingFile2 #-}
168usingFile2 :: (MonadIO m, MonadCatch m)
169 => Unfold m (x, Handle) a -> Unfold m (x, FilePath) a
170usingFile2 = UF.bracketIO before after
174 before (x, file) = do
175 h <- openFile file ReadMode
178 after (_, h) = hClose h
180{-# INLINE usingFile3 #-}
181usingFile3 :: (MonadIO m, MonadCatch m)
182 => Unfold m (x, y, z, Handle) a -> Unfold m (x, y, z, FilePath) a
183usingFile3 = UF.bracketIO before after
187 before (x, y, z, file) = do
188 h <- openFile file ReadMode
191 after (_, _, _, h) = hClose h
193-------------------------------------------------------------------------------
195-------------------------------------------------------------------------------
199-------------------------------------------------------------------------------
201-------------------------------------------------------------------------------
203-- | Write an array to a file. Overwrites the file if it exists.
207{-# INLINABLE putChunk #-}
208putChunk :: FilePath -> Array a -> IO ()
209putChunk file arr = SIO.withFile file WriteMode (`FH.putChunk` arr)
211-- | append an array to a file.
215{-# INLINABLE appendArray #-}
216appendArray :: FilePath -> Array a -> IO ()
217appendArray file arr = SIO.withFile file AppendMode (`FH.putChunk` arr)
219-------------------------------------------------------------------------------
220-- Stream of Arrays IO
221-------------------------------------------------------------------------------
223-- | @readChunksWith size file@ reads a stream of arrays from file @file@.
224-- The maximum size of a single array is specified by @size@. The actual size
225-- read may be less than or equal to @size@.
229{-# INLINE readChunksWith #-}
230readChunksWith :: (MonadIO m, MonadCatch m)
231 => Int -> FilePath -> Stream m (Array Word8)
232readChunksWith size file =
233 withFile file ReadMode (FH.readChunksWith size)
235{-# DEPRECATED toChunksWithBufferOf "Please use 'readChunksWith' instead" #-}
236{-# INLINE toChunksWithBufferOf #-}
237toChunksWithBufferOf :: (MonadIO m, MonadCatch m)
238 => Int -> FilePath -> Stream m (Array Word8)
239toChunksWithBufferOf = readChunksWith
241-- XXX read 'Array a' instead of Word8
243-- | @readChunks file@ reads a stream of arrays from file @file@.
244-- The maximum size of a single array is limited to @defaultChunkSize@. The
245-- actual size read may be less than @defaultChunkSize@.
247-- > readChunks = readChunksWith defaultChunkSize
251{-# INLINE readChunks #-}
252readChunks :: (MonadIO m, MonadCatch m)
253 => FilePath -> Stream m (Array Word8)
254readChunks = readChunksWith defaultChunkSize
256{-# DEPRECATED toChunks "Please use 'readChunks' instead" #-}
257{-# INLINE toChunks #-}
258toChunks :: (MonadIO m, MonadCatch m) => FilePath -> Stream m (Array Word8)
261-------------------------------------------------------------------------------
262-- Read File to Stream
263-------------------------------------------------------------------------------
265-- TODO for concurrent streams implement readahead IO. We can send multiple
266-- read requests at the same time. For serial case we can use async IO. We can
267-- also control the read throughput in mbps or IOPS.
269-- | Unfold the tuple @(bufsize, filepath)@ into a stream of 'Word8' arrays.
270-- Read requests to the IO device are performed using a buffer of size
271-- @bufsize@. The size of an array in the resulting stream is always less than
272-- or equal to @bufsize@.
276{-# INLINE chunkReaderWith #-}
277chunkReaderWith :: (MonadIO m, MonadCatch m)
278 => Unfold m (Int, FilePath) (Array Word8)
279chunkReaderWith = usingFile2 FH.chunkReaderWith
281{-# DEPRECATED readChunksWithBufferOf
282 "Please use 'chunkReaderWith' instead" #-}
283{-# INLINE readChunksWithBufferOf #-}
284readChunksWithBufferOf :: (MonadIO m, MonadCatch m)
285 => Unfold m (Int, FilePath) (Array Word8)
286readChunksWithBufferOf = chunkReaderWith
288-- | Unfold the tuple @(from, to, bufsize, filepath)@ into a stream
290-- Read requests to the IO device are performed using a buffer of size
291-- @bufsize@ starting from absolute offset of @from@ till the absolute
292-- position of @to@. The size of an array in the resulting stream is always
293-- less than or equal to @bufsize@.
296{-# INLINE chunkReaderFromToWith #-}
297chunkReaderFromToWith :: (MonadIO m, MonadCatch m) =>
298 Unfold m (Int, Int, Int, FilePath) (Array Word8)
299chunkReaderFromToWith = usingFile3 FH.chunkReaderFromToWith
301{-# DEPRECATED readChunksFromToWith
302 "Please use 'chunkReaderFromToWith' instead" #-}
303{-# INLINE readChunksFromToWith #-}
304readChunksFromToWith :: (MonadIO m, MonadCatch m) =>
305 Unfold m (Int, Int, Int, FilePath) (Array Word8)
306readChunksFromToWith = chunkReaderFromToWith
308-- | Unfolds a 'FilePath' into a stream of 'Word8' arrays. Requests to the IO
309-- device are performed using a buffer of size
310-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'. The
311-- size of arrays in the resulting stream are therefore less than or equal to
312-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'.
315{-# INLINE chunkReader #-}
316chunkReader :: (MonadIO m, MonadCatch m) => Unfold m FilePath (Array Word8)
317chunkReader = usingFile FH.chunkReader
319-- | Unfolds the tuple @(bufsize, filepath)@ into a byte stream, read requests
320-- to the IO device are performed using buffers of @bufsize@.
323{-# INLINE readerWith #-}
324readerWith :: (MonadIO m, MonadCatch m) => Unfold m (Int, FilePath) Word8
325readerWith = usingFile2 FH.readerWith
327{-# DEPRECATED readWithBufferOf "Please use 'readerWith' instead" #-}
328{-# INLINE readWithBufferOf #-}
329readWithBufferOf :: (MonadIO m, MonadCatch m) =>
330 Unfold m (Int, FilePath) Word8
331readWithBufferOf = readerWith
333-- | Unfolds a file path into a byte stream. IO requests to the device are
334-- performed in sizes of
335-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'.
339reader :: (MonadIO m, MonadCatch m) => Unfold m FilePath Word8
340reader = UF.many A.reader (usingFile FH.chunkReader)
342-- | Generate a stream of bytes from a file specified by path. The stream ends
343-- when EOF is encountered. File is locked using multiple reader and single
344-- writer locking mode.
349read :: (MonadIO m, MonadCatch m) => FilePath -> Stream m Word8
350read file = AS.concat $ withFile file ReadMode FH.readChunks
352{-# DEPRECATED toBytes "Please use 'read' instead" #-}
353{-# INLINE toBytes #-}
354toBytes :: (MonadIO m, MonadCatch m) => FilePath -> Stream m Word8
358-- | Generate a stream of elements of the given type from a file 'Handle'. The
359-- stream ends when EOF is encountered. File is not locked for exclusive reads,
360-- writers can keep writing to the file.
363{-# INLINE readShared #-}
364readShared :: MonadIO m => Handle -> Stream m Word8
365readShared = undefined
368-------------------------------------------------------------------------------
370-------------------------------------------------------------------------------
372{-# INLINE fromChunksMode #-}
373fromChunksMode :: (MonadIO m, MonadCatch m)
374 => IOMode -> FilePath -> Stream m (Array a) -> m ()
375fromChunksMode mode file xs = S.fold drain $
376 withFile file mode (\h -> S.mapM (FH.putChunk h) xs)
378-- | Write a stream of arrays to a file. Overwrites the file if it exists.
382{-# INLINE fromChunks #-}
383fromChunks :: (MonadIO m, MonadCatch m)
384 => FilePath -> Stream m (Array a) -> m ()
385fromChunks = fromChunksMode WriteMode
387-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
390-- Note that if you use a chunk size less than 8K (GHC's default buffer
391-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
392-- do not want buffering to occur at GHC level as well. Same thing applies to
395-- | Like 'write' but provides control over the write buffer. Output will
396-- be written to the IO device as soon as we collect the specified number of
401{-# INLINE fromBytesWith #-}
402fromBytesWith :: (MonadIO m, MonadCatch m)
403 => Int -> FilePath -> Stream m Word8 -> m ()
404fromBytesWith n file xs = fromChunks file $ AS.arraysOf n xs
406{-# DEPRECATED fromBytesWithBufferOf "Please use 'fromBytesWith' instead" #-}
407{-# INLINE fromBytesWithBufferOf #-}
408fromBytesWithBufferOf :: (MonadIO m, MonadCatch m)
409 => Int -> FilePath -> Stream m Word8 -> m ()
410fromBytesWithBufferOf = fromBytesWith
412-- > write = 'writeWith' defaultChunkSize
414-- | Write a byte stream to a file. Combines the bytes in chunks of size
415-- up to 'A.defaultChunkSize' before writing. If the file exists it is
416-- truncated to zero size before writing. If the file does not exist it is
417-- created. File is locked using single writer locking mode.
420{-# INLINE fromBytes #-}
421fromBytes :: (MonadIO m, MonadCatch m) => FilePath -> Stream m Word8 -> m ()
422fromBytes = fromBytesWith defaultChunkSize
426write :: (MonadIO m, Storable a) => Handle -> Stream m a -> m ()
427write = toHandleWith A.defaultChunkSize
430-- | Write a stream of chunks to a handle. Each chunk in the stream is written
431-- to the device as a separate IO request.
434{-# INLINE writeChunks #-}
435writeChunks :: (MonadIO m, MonadCatch m)
436 => FilePath -> Fold m (Array a) ()
437writeChunks path = Fold step initial extract
440 h <- liftIO (openFile path WriteMode)
441 fld <- FL.reduce (FH.writeChunks h)
442 `MC.onException` liftIO (hClose h)
443 return $ FL.Partial (fld, h)
445 r <- FL.snoc fld x `MC.onException` liftIO (hClose h)
446 return $ FL.Partial (r, h)
447 extract (Fold _ initial1 extract1, h) = do
451 FL.Partial fs -> extract1 fs
452 FL.Done fb -> return fb
454-- | @writeWith chunkSize handle@ writes the input stream to @handle@.
455-- Bytes in the input stream are collected into a buffer until we have a chunk
456-- of size @chunkSize@ and then written to the IO device.
459{-# INLINE writeWith #-}
460writeWith :: (MonadIO m, MonadCatch m)
461 => Int -> FilePath -> Fold m Word8 ()
463 chunksOf n (writeNUnsafe n) (writeChunks path)
465{-# DEPRECATED writeWithBufferOf "Please use 'writeWith' instead" #-}
466{-# INLINE writeWithBufferOf #-}
467writeWithBufferOf :: (MonadIO m, MonadCatch m)
468 => Int -> FilePath -> Fold m Word8 ()
469writeWithBufferOf = writeWith
471-- > write = 'writeWith' A.defaultChunkSize
473-- | Write a byte stream to a file. Accumulates the input in chunks of up to
474-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize' before writing to
480write :: (MonadIO m, MonadCatch m) => FilePath -> Fold m Word8 ()
481write = writeWith defaultChunkSize
483-- | Append a stream of arrays to a file.
487{-# INLINE appendChunks #-}
488appendChunks :: (MonadIO m, MonadCatch m)
489 => FilePath -> Stream m (Array a) -> m ()
490appendChunks = fromChunksMode AppendMode
492-- | Like 'append' but provides control over the write buffer. Output will
493-- be written to the IO device as soon as we collect the specified number of
498{-# INLINE appendWith #-}
499appendWith :: (MonadIO m, MonadCatch m)
500 => Int -> FilePath -> Stream m Word8 -> m ()
501appendWith n file xs = appendChunks file $ AS.arraysOf n xs
503-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
504-- 'A.defaultChunkSize' before writing. If the file exists then the new data
505-- is appended to the file. If the file does not exist it is created. File is
506-- locked using single writer locking mode.
511append :: (MonadIO m, MonadCatch m) => FilePath -> Stream m Word8 -> m ()
512append = appendWith defaultChunkSize
515-- | Like 'append' but the file is not locked for exclusive writes.
518{-# INLINE appendShared #-}
519appendShared :: MonadIO m => Handle -> Stream m Word8 -> m ()
520appendShared = undefined
523-------------------------------------------------------------------------------
524-- IO with encoding/decoding Unicode characters
525-------------------------------------------------------------------------------
529-- > readUtf8 = decodeUtf8 . read
531-- Read a UTF8 encoded stream of unicode characters from a file handle.
534{-# INLINE readUtf8 #-}
535readUtf8 :: MonadIO m => Handle -> Stream m Char
536readUtf8 = decodeUtf8 . read
539-- > writeUtf8 h s = write h $ encodeUtf8 s
541-- Encode a stream of unicode characters to UTF8 and write it to the given file
542-- handle. Default block buffering applies to the writes.
545{-# INLINE writeUtf8 #-}
546writeUtf8 :: MonadIO m => Handle -> Stream m Char -> m ()
547writeUtf8 h s = write h $ encodeUtf8 s
549-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
550-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
551-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
552-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
556{-# INLINE writeUtf8ByLines #-}
557writeUtf8ByLines :: MonadIO m => Handle -> Stream m Char -> m ()
558writeUtf8ByLines = undefined
560-- | Read UTF-8 lines from a file handle and apply the specified fold to each
561-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
564{-# INLINE readLines #-}
565readLines :: MonadIO m => Handle -> Fold m Char b -> Stream m b
566readLines h f = foldLines (readUtf8 h) f
568-------------------------------------------------------------------------------
569-- Framing on a sequence
570-------------------------------------------------------------------------------
572-- | Read a stream from a file handle and split it into frames delimited by
573-- the specified sequence of elements. The supplied fold is applied on each
577{-# INLINE readFrames #-}
578readFrames :: (MonadIO m, Storable a)
579 => Array a -> Handle -> Fold m a b -> Stream m b
580readFrames = undefined -- foldFrames . read
582-- | Write a stream to the given file handle buffering up to frames separated
583-- by the given sequence or up to a maximum of @defaultChunkSize@.
586{-# INLINE writeByFrames #-}
587writeByFrames :: (MonadIO m, Storable a)
588 => Array a -> Handle -> Stream m a -> m ()
589writeByFrames = undefined
591-------------------------------------------------------------------------------
592-- Random Access IO (Seek)
593-------------------------------------------------------------------------------
595-- XXX handles could be shared, so we may not want to use the handle state at
596-- all for these APIs. we can use pread and pwrite instead. On windows we will
597-- need to use readFile/writeFile with an offset argument.
599-------------------------------------------------------------------------------
601-- | Read the element at the given index treating the file as an array.
604{-# INLINE readIndex #-}
605readIndex :: Storable a => Handle -> Int -> Maybe a
606readIndex arr i = undefined
608-- NOTE: To represent a range to read we have chosen (start, size) instead of
609-- (start, end). This helps in removing the ambiguity of whether "end" is
610-- included in the range or not.
612-- We could avoid specifying the range to be read and instead use "take size"
613-- on the stream, but it may end up reading more and then consume it partially.
615-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
616-- from @handle@ starting at the offset @pos@ from the beginning of the file.
618-- Reads are performed in chunks of size @chunkSize@. For block devices, to
619-- avoid reading partial blocks @chunkSize@ must align with the block size of
620-- the underlying device. If the underlying block size is unknown, it is a good
621-- idea to keep it a multiple 4KiB. This API ensures that the start of each
622-- chunk is aligned with @chunkSize@ from second chunk onwards.
624{-# INLINE readSliceWith #-}
625readSliceWith :: (MonadIO m, Storable a)
626 => Int -> Handle -> Int -> Int -> Stream m a
627readSliceWith chunkSize h pos len = undefined
629-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
630-- at index @i@ and reading up to @count@ elements in the forward direction
631-- ending at the index @i + count - 1@.
634{-# INLINE readSlice #-}
635readSlice :: (MonadIO m, Storable a)
636 => Handle -> Int -> Int -> Stream m a
637readSlice = readSliceWith defaultChunkSize
639-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
640-- at index @i@ and reading up to @count@ elements in the reverse direction
641-- ending at the index @i - count + 1@.
644{-# INLINE readSliceRev #-}
645readSliceRev :: (MonadIO m, Storable a)
646 => Handle -> Int -> Int -> Stream m a
647readSliceRev h i count = undefined
649-- | Write the given element at the given index in the file.
652{-# INLINE writeIndex #-}
653writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
654writeIndex h i a = undefined
656-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
657-- starting at index @i@ and writing up to @count@ elements in the forward
658-- direction ending at the index @i + count - 1@.
661{-# INLINE writeSlice #-}
662writeSlice :: (Monad m, Storable a)
663 => Handle -> Int -> Int -> Stream m a -> m ()
664writeSlice h i len s = undefined
666-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
667-- starting at index @i@ and writing up to @count@ elements in the reverse
668-- direction ending at the index @i - count + 1@.
671{-# INLINE writeSliceRev #-}
672writeSliceRev :: (Monad m, Storable a)
673 => Handle -> Int -> Int -> Stream m a -> m ()
674writeSliceRev 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