2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
10-- Module : Streamly.FileSystem.FD
11-- Copyright : (c) 2019 Composewell Technologies
14-- Maintainer : harendra.kumar@gmail.com
15-- Stability : experimental
18-- This module is a an experimental replacement for
19-- "Streamly.FileSystem.Handle". The former module provides IO facilities based
20-- on the GHC Handle type. The APIs in this module avoid the GHC handle layer
21-- and provide more explicit control over buffering.
23-- Read and write data as streams and arrays to and from files.
25-- This module provides read and write APIs based on handles. Before reading or
26-- writing, a file must be opened first using 'openFile'. The 'Handle' returned
27-- by 'openFile' is then used to access the file. A 'Handle' is backed by an
28-- operating system file descriptor. When the 'Handle' is garbage collected the
29-- underlying file descriptor is automatically closed. A handle can be
30-- explicitly closed using 'closeFile'.
32-- Reading and writing APIs are divided into two categories, sequential
33-- streaming APIs and random or seekable access APIs. File IO APIs are quite
34-- similar to "Streamly.Mem.Array" read write APIs. In that regard, arrays can
35-- be considered as in-memory files or files can be considered as on-disk
38-- > import qualified Streamly.FileSystem.FD as FD
41module Streamly.FileSystem.FD
50 -- TODO file path based APIs
55 -- | Streaming APIs read or write data to or from a file or device
56 -- sequentially, they never perform a seek to a random location. When
57 -- reading, the stream is lazy and generated on-demand as the consumer
58 -- consumes it. Read IO requests to the IO device are performed in chunks
59 -- of 32KiB, this is referred to as @defaultChunkSize@ in the
60 -- documentation. One IO request may or may not read the full chunk. If the
61 -- whole stream is not consumed, it is possible that we may read slightly
62 -- more from the IO device than what the consumer needed. Unless specified
63 -- otherwise in the API, writes are collected into chunks of
64 -- @defaultChunkSize@ before they are written to the IO device.
66 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
67 -- including disks, files, memory devices, terminals, pipes, sockets and
68 -- fifos. While random access APIs work only for files or devices that have
69 -- random access or seek capability for example disks, memory devices.
70 -- Devices like terminals, pipes, sockets and fifos do not have random
73 -- ** Read File to Stream
88 -- ** Write File from Stream
98 , writeArraysPackedUpto
100 -- XXX these are incomplete
102 -- , writevArraysPackedUpto
104 -- -- * Random Access (Seek)
105 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
106 -- files that have random access or seek capability. This type of devices
107 -- include disks, files, memory devices and exclude terminals, pipes,
108 -- sockets and fifos.
113 -- , readAt -- read from a given position to th end of file
114 -- , readSliceArrayUpto
115 -- , readSliceArrayOf
120 -- , writeAt -- start writing at the given position
125import Control.Monad.IO.Class (MonadIO(..))
126import Data.Word (Word8)
127import Foreign.ForeignPtr (withForeignPtr)
128-- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
129import Foreign.Ptr (plusPtr, castPtr)
130import Foreign.Storable (Storable(..))
131import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
132-- import System.IO (Handle, hGetBufSome, hPutBuf)
133import System.IO (IOMode)
134import Prelude hiding (read)
136import qualified GHC.IO.FD as FD
137import qualified GHC.IO.Device as RawIO
139import Streamly.Mem.Array.Types (Array(..))
140import Streamly.Streams.Serial (SerialT)
141import Streamly.Streams.StreamK.Type (IsStream, mkStream)
142import Streamly.Mem.Array.Types (byteLength, defaultChunkSize)
144#if !defined(mingw32_HOST_OS)
145import Streamly.Mem.Array.Types (groupIOVecsOf)
146import Streamly.Streams.StreamD (toStreamD)
147import Streamly.Streams.StreamD.Type (fromStreamD)
148import qualified Streamly.FileSystem.FDIO as RawIO hiding (write)
150-- import Streamly.Fold (Fold)
151-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
153import qualified Streamly.Mem.Array as A
154import qualified Streamly.Mem.Array.Stream as AS
155import qualified Streamly.Prelude as S
156import qualified Streamly.Streams.StreamD.Type as D
158-------------------------------------------------------------------------------
160-------------------------------------------------------------------------------
162-- The following references may be useful to build an understanding about the
165-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
166-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
167-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
168-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
169-- https://www.w3.org/TR/FileAPI/ for http file API.
171-------------------------------------------------------------------------------
173-------------------------------------------------------------------------------
175-- XXX attach a finalizer
176-- | A 'Handle' is returned by 'openFile' and is subsequently used to perform
177-- read and write operations on a file.
179newtype Handle = Handle FD.FD
181-- | File handle for standard input
183stdin = Handle FD.stdin
185-- | File handle for standard output
187stdout = Handle FD.stdout
189-- | File handle for standard error
191stderr = Handle FD.stderr
193-- XXX we can support all the flags that the "open" system call supports.
194-- Instead of using RTS locking mechanism can we use system provided locking
197-- | Open a file that is not a directory and return a file handle.
198-- 'openFile' enforces a multiple-reader single-writer locking on files. That
199-- is, there may either be many handles on the same file which manage input, or
200-- just one handle on the file which manages output. If any open handle is
201-- managing a file for output, no new handle can be allocated for that file. If
202-- any open handle is managing a file for input, new handles can only be
203-- allocated if they do not manage output. Whether two files are the same is
204-- implementation-dependent, but they should normally be the same if they have
205-- the same absolute path name and neither has been renamed, for example.
207openFile :: FilePath -> IOMode -> IO Handle
208openFile path mode = fmap (Handle . fst) $ FD.openFile path mode True
210-------------------------------------------------------------------------------
212-------------------------------------------------------------------------------
214-- | Read a 'ByteArray' from a file handle. If no data is available on the
215-- handle it blocks until some data becomes available. If data is available
216-- then it immediately returns that data without blocking. It reads a maximum
217-- of up to the size requested.
218{-# INLINABLE readArrayUpto #-}
219readArrayUpto :: Int -> Handle -> IO (Array Word8)
220readArrayUpto size (Handle fd) = do
221 ptr <- mallocPlainForeignPtrBytes size
222 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
223 withForeignPtr ptr $ \p -> do
224 -- n <- hGetBufSome h p size
225 n <- RawIO.read fd p size
228 , aEnd = p `plusPtr` n
229 , aBound = p `plusPtr` size
231 -- XXX shrink only if the diff is significant
235-------------------------------------------------------------------------------
237-------------------------------------------------------------------------------
239-- | Write an 'Array' to a file handle.
242{-# INLINABLE writeArray #-}
243writeArray :: Storable a => Handle -> Array a -> IO ()
244writeArray _ arr | A.length arr == 0 = return ()
245writeArray (Handle fd) arr = withForeignPtr (aStart arr) $ \p -> do
246 -- RawIO.writeAll fd (castPtr p) aLen
247 RawIO.write fd (castPtr p) aLen
249 -- Experiment to compare "writev" based IO with "write" based IO.
251 let iov' = iov {aEnd = aBound iov}
252 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
253 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
256 aLen = byteLength arr
258#if !defined(mingw32_HOST_OS)
259-- | Write an array of 'IOVec' to a file handle.
262{-# INLINABLE writeIOVec #-}
263writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
264writeIOVec _ iov | A.length iov == 0 = return ()
265writeIOVec (Handle fd) iov =
266 withForeignPtr (aStart iov) $ \p ->
267 RawIO.writevAll fd p (A.length iov)
270-------------------------------------------------------------------------------
271-- Stream of Arrays IO
272-------------------------------------------------------------------------------
274-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
275-- The maximum size of a single array is specified by @size@. The actual size
276-- read may be less than or equal to @size@.
277{-# INLINABLE _readArraysOfUpto #-}
278_readArraysOfUpto :: (IsStream t, MonadIO m)
279 => Int -> Handle -> t m (Array Word8)
280_readArraysOfUpto size h = go
282 -- XXX use cons/nil instead
283 go = mkStream $ \_ yld _ stp -> do
284 arr <- liftIO $ readArrayUpto size h
289{-# INLINE_NORMAL readArraysOfUpto #-}
290readArraysOfUpto :: (IsStream t, MonadIO m)
291 => Int -> Handle -> t m (Array Word8)
292readArraysOfUpto size h = D.fromStreamD (D.Stream step ())
294 {-# INLINE_LATE step #-}
296 arr <- liftIO $ readArrayUpto size h
302-- XXX read 'Array a' instead of Word8
304-- | @readArrays h@ reads a stream of arrays from file handle @h@.
305-- The maximum size of a single array is limited to @defaultChunkSize@.
306-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
309-- > readArrays = readArraysOfUpto defaultChunkSize
312{-# INLINE readArrays #-}
313readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
314readArrays = readArraysOfUpto defaultChunkSize
316-------------------------------------------------------------------------------
317-- Read File to Stream
318-------------------------------------------------------------------------------
320-- TODO for concurrent streams implement readahead IO. We can send multiple
321-- read requests at the same time. For serial case we can use async IO. We can
322-- also control the read throughput in mbps or IOPS.
324-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file handle,
325-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
326-- as EOF is encountered.
328{-# INLINE readByChunksUpto #-}
329readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
330readByChunksUpto chunkSize h = AS.flatten $ readArraysOfUpto chunkSize h
333-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
335-- > read = 'readByChunks' A.defaultChunkSize
336-- | Generate a stream of elements of the given type from a file 'Handle'. The
337-- stream ends when EOF is encountered.
341read :: (IsStream t, MonadIO m) => Handle -> t m Word8
342read = AS.flatten . readArrays
344-------------------------------------------------------------------------------
346-------------------------------------------------------------------------------
348-- | Write a stream of arrays to a handle.
351{-# INLINE writeArrays #-}
352writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
353writeArrays h m = S.mapM_ (liftIO . writeArray h) m
355-- | Write a stream of arrays to a handle after coalescing them in chunks of
356-- specified size. The chunk size is only a maximum and the actual writes could
357-- be smaller than that as we do not split the arrays to fit them to the
361{-# INLINE writeArraysPackedUpto #-}
362writeArraysPackedUpto :: (MonadIO m, Storable a)
363 => Int -> Handle -> SerialT m (Array a) -> m ()
364writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
366#if !defined(mingw32_HOST_OS)
367-- XXX this is incomplete
368-- | Write a stream of 'IOVec' arrays to a handle.
372writev :: MonadIO m => Handle -> SerialT m (Array RawIO.IOVec) -> m ()
373writev h m = S.mapM_ (liftIO . writeIOVec h) m
375-- XXX this is incomplete
376-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
377-- of up to a maximum total size. Writes are performed using gather IO via
378-- @writev@ system call. The maximum number of entries in each 'IOVec' group
382{-# INLINE _writevArraysPackedUpto #-}
383_writevArraysPackedUpto :: MonadIO m
384 => Int -> Handle -> SerialT m (Array a) -> m ()
385_writevArraysPackedUpto n h xs =
386 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
389-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
392-- Note that if you use a chunk size less than 8K (GHC's default buffer
393-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
394-- do not want buffering to occur at GHC level as well. Same thing applies to
397-- | Like 'write' but provides control over the write buffer. Output will
398-- be written to the IO device as soon as we collect the specified number of
402{-# INLINE writeByChunksOf #-}
403writeByChunksOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
404writeByChunksOf n h m = writeArrays h $ AS.arraysOf n m
406-- > write = 'writeByChunks' A.defaultChunkSize
408-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
409-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
410-- depends on the 'IOMode' and the current seek position of the handle.
414write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
415write = writeByChunksOf defaultChunkSize
419write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
420write = toHandleWith A.defaultChunkSize
423-------------------------------------------------------------------------------
424-- IO with encoding/decoding Unicode characters
425-------------------------------------------------------------------------------
429-- > readUtf8 = decodeUtf8 . read
431-- Read a UTF8 encoded stream of unicode characters from a file handle.
434{-# INLINE readUtf8 #-}
435readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
436readUtf8 = decodeUtf8 . read
439-- > writeUtf8 h s = write h $ encodeUtf8 s
441-- Encode a stream of unicode characters to UTF8 and write it to the given file
442-- handle. Default block buffering applies to the writes.
445{-# INLINE writeUtf8 #-}
446writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
447writeUtf8 h s = write h $ encodeUtf8 s
449-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
450-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
451-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
452-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
456{-# INLINE writeUtf8ByLines #-}
457writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
458writeUtf8ByLines = undefined
460-- | Read UTF-8 lines from a file handle and apply the specified fold to each
461-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
464{-# INLINE readLines #-}
465readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
466readLines h f = foldLines (readUtf8 h) f
468-------------------------------------------------------------------------------
469-- Framing on a sequence
470-------------------------------------------------------------------------------
472-- | Read a stream from a file handle and split it into frames delimited by
473-- the specified sequence of elements. The supplied fold is applied on each
477{-# INLINE readFrames #-}
478readFrames :: (IsStream t, MonadIO m, Storable a)
479 => Array a -> Handle -> Fold m a b -> t m b
480readFrames = undefined -- foldFrames . read
482-- | Write a stream to the given file handle buffering up to frames separated
483-- by the given sequence or up to a maximum of @defaultChunkSize@.
486{-# INLINE writeByFrames #-}
487writeByFrames :: (IsStream t, MonadIO m, Storable a)
488 => Array a -> Handle -> t m a -> m ()
489writeByFrames = undefined
491-------------------------------------------------------------------------------
492-- Random Access IO (Seek)
493-------------------------------------------------------------------------------
495-- XXX handles could be shared, so we may not want to use the handle state at
496-- all for these APIs. we can use pread and pwrite instead. On windows we will
497-- need to use readFile/writeFile with an offset argument.
499-------------------------------------------------------------------------------
501-- | Read the element at the given index treating the file as an array.
504{-# INLINE readIndex #-}
505readIndex :: Storable a => Handle -> Int -> Maybe a
506readIndex arr i = undefined
508-- NOTE: To represent a range to read we have chosen (start, size) instead of
509-- (start, end). This helps in removing the ambiguity of whether "end" is
510-- included in the range or not.
512-- We could avoid specifying the range to be read and instead use "take size"
513-- on the stream, but it may end up reading more and then consume it partially.
515-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
516-- from @handle@ starting at the offset @pos@ from the beginning of the file.
518-- Reads are performed in chunks of size @chunkSize@. For block devices, to
519-- avoid reading partial blocks @chunkSize@ must align with the block size of
520-- the underlying device. If the underlying block size is unknown, it is a good
521-- idea to keep it a multiple 4KiB. This API ensures that the start of each
522-- chunk is aligned with @chunkSize@ from second chunk onwards.
524{-# INLINE readSliceWith #-}
525readSliceWith :: (IsStream t, MonadIO m, Storable a)
526 => Int -> Handle -> Int -> Int -> t m a
527readSliceWith chunkSize h pos len = undefined
529-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
530-- at index @i@ and reading up to @count@ elements in the forward direction
531-- ending at the index @i + count - 1@.
534{-# INLINE readSlice #-}
535readSlice :: (IsStream t, MonadIO m, Storable a)
536 => Handle -> Int -> Int -> t m a
537readSlice = readSliceWith A.defaultChunkSize
539-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
540-- at index @i@ and reading up to @count@ elements in the reverse direction
541-- ending at the index @i - count + 1@.
544{-# INLINE readSliceRev #-}
545readSliceRev :: (IsStream t, MonadIO m, Storable a)
546 => Handle -> Int -> Int -> t m a
547readSliceRev h i count = undefined
549-- | Write the given element at the given index in the file.
552{-# INLINE writeIndex #-}
553writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
554writeIndex h i a = undefined
556-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
557-- starting at index @i@ and writing up to @count@ elements in the forward
558-- direction ending at the index @i + count - 1@.
561{-# INLINE writeSlice #-}
562writeSlice :: (IsStream t, Monad m, Storable a)
563 => Handle -> Int -> Int -> t m a -> m ()
564writeSlice h i len s = undefined
566-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
567-- starting at index @i@ and writing up to @count@ elements in the reverse
568-- direction ending at the index @i - count + 1@.
571{-# INLINE writeSliceRev #-}
572writeSliceRev :: (IsStream t, Monad m, Storable a)
573 => Handle -> Int -> Int -> t m a -> m ()
574writeSliceRev 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