2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
11-- Module : Streamly.FileSystem.File
12-- Copyright : (c) 2019 Harendra Kumar
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
19-- Read and write streams and arrays to and from files specified by their paths
20-- in the file system. Unlike the handle based APIs which can have a read/write
21-- session consisting of multiple reads and writes to the handle, these APIs
22-- are one shot read or write APIs. These APIs open the file handle, perform
23-- the requested operation and close the handle. Thease are safer compared to
24-- the handle based APIs as there is no possiblity of a file descriptor
27-- > import qualified Streamly.FileSystem.File as File
30module Streamly.FileSystem.File
33 -- | Stream data to or from a file or device sequentially. When reading,
34 -- the stream is lazy and generated on-demand as the consumer consumes it.
35 -- Read IO requests to the IO device are performed in chunks limited to a
36 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
37 -- documentation. One IO request may or may not read the full
38 -- chunk. If the whole stream is not consumed, it is possible that we may
39 -- read slightly more from the IO device than what the consumer needed.
40 -- Unless specified otherwise in the API, writes are collected into chunks
41 -- of @defaultChunkSize@ before they are written to the IO device.
43 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
44 -- including disks, files, memory devices, terminals, pipes, sockets and
45 -- fifos. While random access APIs work only for files or devices that have
46 -- random access or seek capability for example disks, memory devices.
47 -- Devices like terminals, pipes, sockets and fifos do not have random
50 -- ** File IO Using Handle
88 -- -- * Random Access (Seek)
89 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
90 -- files that have random access or seek capability. This type of devices
91 -- include disks, files, memory devices and exclude terminals, pipes,
97 -- , readAt -- read from a given position to th end of file
98 -- , readSliceArrayUpto
104 -- , writeAt -- start writing at the given position
109import Control.Monad.Catch (MonadCatch)
110import Control.Monad.IO.Class (MonadIO(..))
111import Data.Word (Word8)
112import Foreign.Storable (Storable(..))
113import System.IO (Handle, openFile, IOMode(..), hClose)
114import Prelude hiding (read)
116import qualified System.IO as SIO
118import Streamly.Memory.Array.Types (Array(..), defaultChunkSize)
119import Streamly.Streams.Serial (SerialT)
120import Streamly.Streams.StreamK.Type (IsStream)
121import Streamly.SVar (MonadAsync)
122-- import Streamly.Fold (Fold)
123-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
125import qualified Streamly.FileSystem.Handle as FH
126import qualified Streamly.Memory.Array as A
127import qualified Streamly.Prelude as S
129-------------------------------------------------------------------------------
131-------------------------------------------------------------------------------
133-- The following references may be useful to build an understanding about the
136-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
137-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
138-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
139-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
140-- https://www.w3.org/TR/FileAPI/ for http file API.
142-------------------------------------------------------------------------------
144-------------------------------------------------------------------------------
146-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
147-- the resulting handle to the computation @act@. The handle will be
148-- closed on exit from 'withFile', whether by normal termination or by
149-- raising an exception. If closing the handle raises an exception, then
150-- this exception will be raised by 'withFile' rather than any exception
152{-# INLINE withFile #-}
153withFile :: (IsStream t, MonadCatch m, MonadIO m)
154 => FilePath -> IOMode -> (Handle -> t m a) -> t m a
155withFile file mode = S.bracket (liftIO $ openFile file mode) (liftIO . hClose)
157-------------------------------------------------------------------------------
159-------------------------------------------------------------------------------
163-------------------------------------------------------------------------------
165-------------------------------------------------------------------------------
167-- | Write an array to a file. Overwrites the file if it exists.
170{-# INLINABLE writeArray #-}
171writeArray :: Storable a => FilePath -> Array a -> IO ()
172writeArray file arr = SIO.withFile file WriteMode (\h -> FH.writeArray h arr)
174-- | append an array to a file.
177{-# INLINABLE appendArray #-}
178appendArray :: Storable a => FilePath -> Array a -> IO ()
179appendArray file arr = SIO.withFile file AppendMode (\h -> FH.writeArray h arr)
181-------------------------------------------------------------------------------
182-- Stream of Arrays IO
183-------------------------------------------------------------------------------
185-- | @readArraysOf size file@ reads a stream of arrays from file @file@.
186-- The maximum size of a single array is specified by @size@. The actual size
187-- read may be less than or equal to @size@.
188{-# INLINABLE readArraysOf #-}
189readArraysOf :: (IsStream t, MonadCatch m, MonadIO m)
190 => Int -> FilePath -> t m (Array Word8)
191readArraysOf size file = withFile file ReadMode (FH.readArraysOf size)
193-- XXX read 'Array a' instead of Word8
195-- | @readArrays file@ reads a stream of arrays from file @file@.
196-- The maximum size of a single array is limited to @defaultChunkSize@. The
197-- actual size read may be less than @defaultChunkSize@.
199-- > readArrays = readArraysOf defaultChunkSize
202{-# INLINE readArrays #-}
203readArrays :: (IsStream t, MonadCatch m, MonadIO m)
204 => FilePath -> t m (Array Word8)
205readArrays = readArraysOf defaultChunkSize
207-------------------------------------------------------------------------------
208-- Read File to Stream
209-------------------------------------------------------------------------------
211-- TODO for concurrent streams implement readahead IO. We can send multiple
212-- read requests at the same time. For serial case we can use async IO. We can
213-- also control the read throughput in mbps or IOPS.
216-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file
217-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
218-- as soon as EOF is encountered.
220{-# INLINE readInChunksOf #-}
221readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
222readInChunksOf chunkSize h = A.flattenArrays $ readArraysOf chunkSize h
226-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
228-- > read = 'readByChunks' defaultChunkSize
229-- | Generate a stream of elements of the given type from a file specified by
230-- path. The stream ends when EOF is encountered. File is locked using multiple
231-- reader and single writer locking mode.
235read :: (IsStream t, MonadCatch m, MonadIO m) => FilePath -> t m Word8
236read file = A.concat $ withFile file ReadMode FH.readArrays
239-- | Generate a stream of elements of the given type from a file 'Handle'. The
240-- stream ends when EOF is encountered. File is not locked for exclusive reads,
241-- writers can keep writing to the file.
244{-# INLINE readShared #-}
245readShared :: (IsStream t, MonadIO m) => Handle -> t m Word8
246readShared = undefined
248-- | Read a stream from a given file path. When end of file (EOF) is reached
249-- this API waits for more data to be written to the file and keeps reading it
253{-# INLINE readTailForever #-}
254readTailForever :: (IsStream t, MonadIO m) => Handle -> t m Word8
255readTailForever = undefined
258-------------------------------------------------------------------------------
260-------------------------------------------------------------------------------
262{-# INLINE writeArraysMode #-}
263writeArraysMode :: (MonadAsync m, MonadCatch m, Storable a)
264 => IOMode -> FilePath -> SerialT m (Array a) -> m ()
265writeArraysMode mode file xs = S.drain $
266 withFile file mode (\h -> S.mapM (liftIO . FH.writeArray h) xs)
268-- | Write a stream of arrays to a file. Overwrites the file if it exists.
271{-# INLINE writeArrays #-}
272writeArrays :: (MonadAsync m, MonadCatch m, Storable a)
273 => FilePath -> SerialT m (Array a) -> m ()
274writeArrays = writeArraysMode WriteMode
276-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
279-- Note that if you use a chunk size less than 8K (GHC's default buffer
280-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
281-- do not want buffering to occur at GHC level as well. Same thing applies to
284-- | Like 'write' but provides control over the write buffer. Output will
285-- be written to the IO device as soon as we collect the specified number of
289{-# INLINE writeInChunksOf #-}
290writeInChunksOf :: (MonadAsync m, MonadCatch m)
291 => Int -> FilePath -> SerialT m Word8 -> m ()
292writeInChunksOf n file xs = writeArrays file $ A.arraysOf n xs
294-- > write = 'writeInChunksOf' defaultChunkSize
296-- | Write a byte stream to a file. Combines the bytes in chunks of size
297-- up to 'A.defaultChunkSize' before writing. If the file exists it is
298-- truncated to zero size before writing. If the file does not exist it is
299-- created. File is locked using single writer locking mode.
303write :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
304write = writeInChunksOf defaultChunkSize
308write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
309write = toHandleWith A.defaultChunkSize
312-- | Append a stream of arrays to a file.
315{-# INLINE appendArrays #-}
316appendArrays :: (MonadAsync m, MonadCatch m, Storable a)
317 => FilePath -> SerialT m (Array a) -> m ()
318appendArrays = writeArraysMode AppendMode
320-- | Like 'append' but provides control over the write buffer. Output will
321-- be written to the IO device as soon as we collect the specified number of
325{-# INLINE appendByChunks #-}
326appendByChunks :: (MonadAsync m, MonadCatch m)
327 => Int -> FilePath -> SerialT m Word8 -> m ()
328appendByChunks n file xs = appendArrays file $ A.arraysOf n xs
330-- | Append a byte stream to a file. Combines the bytes in chunks of size up to
331-- 'A.defaultChunkSize' before writing. If the file exists then the new data
332-- is appended to the file. If the file does not exist it is created. File is
333-- locked using single writer locking mode.
337append :: (MonadAsync m, MonadCatch m) => FilePath -> SerialT m Word8 -> m ()
338append = appendByChunks defaultChunkSize
341-- | Like 'append' but the file is not locked for exclusive writes.
344{-# INLINE appendShared #-}
345appendShared :: MonadIO m => Handle -> SerialT m Word8 -> m ()
346appendShared = undefined
349-------------------------------------------------------------------------------
350-- IO with encoding/decoding Unicode characters
351-------------------------------------------------------------------------------
355-- > readUtf8 = decodeUtf8 . read
357-- Read a UTF8 encoded stream of unicode characters from a file handle.
360{-# INLINE readUtf8 #-}
361readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
362readUtf8 = decodeUtf8 . read
365-- > writeUtf8 h s = write h $ encodeUtf8 s
367-- Encode a stream of unicode characters to UTF8 and write it to the given file
368-- handle. Default block buffering applies to the writes.
371{-# INLINE writeUtf8 #-}
372writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
373writeUtf8 h s = write h $ encodeUtf8 s
375-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
376-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
377-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
378-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
382{-# INLINE writeUtf8ByLines #-}
383writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
384writeUtf8ByLines = undefined
386-- | Read UTF-8 lines from a file handle and apply the specified fold to each
387-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
390{-# INLINE readLines #-}
391readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
392readLines h f = foldLines (readUtf8 h) f
394-------------------------------------------------------------------------------
395-- Framing on a sequence
396-------------------------------------------------------------------------------
398-- | Read a stream from a file handle and split it into frames delimited by
399-- the specified sequence of elements. The supplied fold is applied on each
403{-# INLINE readFrames #-}
404readFrames :: (IsStream t, MonadIO m, Storable a)
405 => Array a -> Handle -> Fold m a b -> t m b
406readFrames = undefined -- foldFrames . read
408-- | Write a stream to the given file handle buffering up to frames separated
409-- by the given sequence or up to a maximum of @defaultChunkSize@.
412{-# INLINE writeByFrames #-}
413writeByFrames :: (IsStream t, MonadIO m, Storable a)
414 => Array a -> Handle -> t m a -> m ()
415writeByFrames = undefined
417-------------------------------------------------------------------------------
418-- Random Access IO (Seek)
419-------------------------------------------------------------------------------
421-- XXX handles could be shared, so we may not want to use the handle state at
422-- all for these APIs. we can use pread and pwrite instead. On windows we will
423-- need to use readFile/writeFile with an offset argument.
425-------------------------------------------------------------------------------
427-- | Read the element at the given index treating the file as an array.
430{-# INLINE readIndex #-}
431readIndex :: Storable a => Handle -> Int -> Maybe a
432readIndex arr i = undefined
434-- NOTE: To represent a range to read we have chosen (start, size) instead of
435-- (start, end). This helps in removing the ambiguity of whether "end" is
436-- included in the range or not.
438-- We could avoid specifying the range to be read and instead use "take size"
439-- on the stream, but it may end up reading more and then consume it partially.
441-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
442-- from @handle@ starting at the offset @pos@ from the beginning of the file.
444-- Reads are performed in chunks of size @chunkSize@. For block devices, to
445-- avoid reading partial blocks @chunkSize@ must align with the block size of
446-- the underlying device. If the underlying block size is unknown, it is a good
447-- idea to keep it a multiple 4KiB. This API ensures that the start of each
448-- chunk is aligned with @chunkSize@ from second chunk onwards.
450{-# INLINE readSliceWith #-}
451readSliceWith :: (IsStream t, MonadIO m, Storable a)
452 => Int -> Handle -> Int -> Int -> t m a
453readSliceWith chunkSize h pos len = undefined
455-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
456-- at index @i@ and reading up to @count@ elements in the forward direction
457-- ending at the index @i + count - 1@.
460{-# INLINE readSlice #-}
461readSlice :: (IsStream t, MonadIO m, Storable a)
462 => Handle -> Int -> Int -> t m a
463readSlice = readSliceWith defaultChunkSize
465-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
466-- at index @i@ and reading up to @count@ elements in the reverse direction
467-- ending at the index @i - count + 1@.
470{-# INLINE readSliceRev #-}
471readSliceRev :: (IsStream t, MonadIO m, Storable a)
472 => Handle -> Int -> Int -> t m a
473readSliceRev h i count = undefined
475-- | Write the given element at the given index in the file.
478{-# INLINE writeIndex #-}
479writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
480writeIndex h i a = undefined
482-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
483-- starting at index @i@ and writing up to @count@ elements in the forward
484-- direction ending at the index @i + count - 1@.
487{-# INLINE writeSlice #-}
488writeSlice :: (IsStream t, Monad m, Storable a)
489 => Handle -> Int -> Int -> t m a -> m ()
490writeSlice h i len s = undefined
492-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
493-- starting at index @i@ and writing up to @count@ elements in the reverse
494-- direction ending at the index @i - count + 1@.
497{-# INLINE writeSliceRev #-}
498writeSliceRev :: (IsStream t, Monad m, Storable a)
499 => Handle -> Int -> Int -> t m a -> m ()
500writeSliceRev 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