4-- Module : Streamly.Internal.FileSystem.FD
5-- Copyright : (c) 2019 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
12-- This module is a an experimental replacement for
13-- "Streamly.FileSystem.Handle". The former module provides IO facilities based
14-- on the GHC Handle type. The APIs in this module avoid the GHC handle layer
15-- and provide more explicit control over buffering.
17-- Read and write data as streams and arrays to and from files.
19-- This module provides read and write APIs based on handles. Before reading or
20-- writing, a file must be opened first using 'openFile'. The 'Handle' returned
21-- by 'openFile' is then used to access the file. A 'Handle' is backed by an
22-- operating system file descriptor. When the 'Handle' is garbage collected the
23-- underlying file descriptor is automatically closed. A handle can be
24-- explicitly closed using 'closeFile'.
26-- Reading and writing APIs are divided into two categories, sequential
27-- streaming APIs and random or seekable access APIs. File IO APIs are quite
28-- similar to "Streamly.Data.Array.Foreign" read write APIs. In that regard, arrays can
29-- be considered as in-memory files or files can be considered as on-disk
32-- > import qualified Streamly.Internal.FileSystem.FD as FD
35module Streamly.Internal.FileSystem.FD
44 -- TODO file path based APIs
49 -- | Streaming APIs read or write data to or from a file or device
50 -- sequentially, they never perform a seek to a random location. When
51 -- reading, the stream is lazy and generated on-demand as the consumer
52 -- consumes it. Read IO requests to the IO device are performed in chunks
53 -- of 32KiB, this is referred to as @defaultChunkSize@ in the
54 -- documentation. One IO request may or may not read the full chunk. If the
55 -- whole stream is not consumed, it is possible that we may read slightly
56 -- more from the IO device than what the consumer needed. Unless specified
57 -- otherwise in the API, writes are collected into chunks of
58 -- @defaultChunkSize@ before they are written to the IO device.
60 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
61 -- including disks, files, memory devices, terminals, pipes, sockets and
62 -- fifos. While random access APIs work only for files or devices that have
63 -- random access or seek capability for example disks, memory devices.
64 -- Devices like terminals, pipes, sockets and fifos do not have random
67 -- ** Read File to Stream
82 -- ** Write File from Stream
92 , writeArraysPackedUpto
94 -- XXX these are incomplete
96 -- , writevArraysPackedUpto
98 -- -- * Random Access (Seek)
99 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
100 -- files that have random access or seek capability. This type of devices
101 -- include disks, files, memory devices and exclude terminals, pipes,
102 -- sockets and fifos.
107 -- , readAt -- read from a given position to th end of file
108 -- , readSliceArrayUpto
109 -- , readSliceArrayOf
114 -- , writeAt -- start writing at the given position
119import Control.Monad.IO.Class (MonadIO(..))
120import Data.Word (Word8)
121-- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
122import Foreign.Ptr (castPtr)
123import Streamly.Internal.Data.Unbox (Unbox)
124-- import System.IO (Handle, hGetBufSome, hPutBuf)
125import System.IO (IOMode)
126import Prelude hiding (read)
128import qualified GHC.IO.FD as FD
129import qualified GHC.IO.Device as RawIO
131import Streamly.Data.Array (Array)
132import Streamly.Data.Stream (Stream)
134import Streamly.Internal.Data.Array (byteLength, unsafeFreeze, asPtrUnsafe)
135import Streamly.Internal.System.IO (defaultChunkSize)
137#if !defined(mingw32_HOST_OS)
139import Streamly.Internal.Data.Stream.IsStream.Type (toStreamD)
140import Streamly.Internal.System.IOVec (groupIOVecsOf)
141import qualified Streamly.Internal.FileSystem.FDIO as RawIO hiding (write)
142import qualified Streamly.Internal.System.IOVec.Type as RawIO
145-- import Streamly.Data.Fold (Fold)
146-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
148import qualified Streamly.Data.Array as A
149import qualified Streamly.Data.Fold as FL
150import qualified Streamly.Internal.Data.MutArray as MArray
151 (MutArray(..), asPtrUnsafe, pinnedNewBytes)
152import qualified Streamly.Internal.Data.Stream.Chunked as AS
153import qualified Streamly.Internal.Data.Stream as S
154import qualified Streamly.Internal.Data.Stream as D
155 (Stream(..), Step(..))
156import qualified Streamly.Internal.Data.StreamK as K (mkStream)
159-------------------------------------------------------------------------------
161-------------------------------------------------------------------------------
163-- The following references may be useful to build an understanding about the
166-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
167-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
168-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
169-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
170-- https://www.w3.org/TR/FileAPI/ for http file API.
172-------------------------------------------------------------------------------
174-------------------------------------------------------------------------------
176-- XXX attach a finalizer
177-- | A 'Handle' is returned by 'openFile' and is subsequently used to perform
178-- read and write operations on a file.
180newtype Handle = Handle FD.FD
182-- | File handle for standard input
184stdin = Handle FD.stdin
186-- | File handle for standard output
188stdout = Handle FD.stdout
190-- | File handle for standard error
192stderr = Handle FD.stderr
194-- XXX we can support all the flags that the "open" system call supports.
195-- Instead of using RTS locking mechanism can we use system provided locking
198-- | Open a file that is not a directory and return a file handle.
199-- 'openFile' enforces a multiple-reader single-writer locking on files. That
200-- is, there may either be many handles on the same file which manage input, or
201-- just one handle on the file which manages output. If any open handle is
202-- managing a file for output, no new handle can be allocated for that file. If
203-- any open handle is managing a file for input, new handles can only be
204-- allocated if they do not manage output. Whether two files are the same is
205-- implementation-dependent, but they should normally be the same if they have
206-- the same absolute path name and neither has been renamed, for example.
208openFile :: FilePath -> IOMode -> IO Handle
209openFile path mode = Handle . fst <$> FD.openFile path mode True
211-------------------------------------------------------------------------------
213-------------------------------------------------------------------------------
215-- | Read a 'ByteArray' from a file handle. If no data is available on the
216-- handle it blocks until some data becomes available. If data is available
217-- then it immediately returns that data without blocking. It reads a maximum
218-- of up to the size requested.
219{-# INLINABLE readArrayUpto #-}
220readArrayUpto :: Int -> Handle -> IO (Array Word8)
221readArrayUpto size (Handle fd) = do
222 arr <- MArray.pinnedNewBytes size
223 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
224 MArray.asPtrUnsafe arr $ \p -> do
225 -- n <- hGetBufSome h p size
226#if MIN_VERSION_base(4,15,0)
227 n <- RawIO.read fd p 0 size
229 n <- RawIO.read fd p size
231 -- XXX shrink only if the diff is significant
232 -- Use unsafeFreezeWithShrink
235 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
237-------------------------------------------------------------------------------
239-------------------------------------------------------------------------------
241-- | Write an 'Array' to a file handle.
244{-# INLINABLE writeArray #-}
245writeArray :: Unbox a => Handle -> Array a -> IO ()
246writeArray _ arr | A.length arr == 0 = return ()
247writeArray (Handle fd) arr =
248 asPtrUnsafe arr $ \p ->
249 -- RawIO.writeAll fd (castPtr p) aLen
250#if MIN_VERSION_base(4,15,0)
251 RawIO.write fd (castPtr p) 0 aLen
253 RawIO.write fd (castPtr p) aLen
256 -- Experiment to compare "writev" based IO with "write" based IO.
258 let iov' = iov {arrEnd = arrBound iov}
259 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
260 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
263 aLen = byteLength arr
265#if !defined(mingw32_HOST_OS)
267-- | Write an array of 'IOVec' to a file handle.
270{-# INLINABLE writeIOVec #-}
271writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
272writeIOVec _ iov | A.length iov == 0 = return ()
273writeIOVec (Handle fd) iov =
274 asPtrUnsafe iov $ \p ->
275 RawIO.writevAll fd p (A.length iov)
279-------------------------------------------------------------------------------
280-- Stream of Arrays IO
281-------------------------------------------------------------------------------
283-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
284-- The maximum size of a single array is specified by @size@. The actual size
285-- read may be less than or equal to @size@.
286{-# INLINE _readArraysOfUpto #-}
287_readArraysOfUpto :: (MonadIO m)
288 => Int -> Handle -> Stream m (Array Word8)
289_readArraysOfUpto size h = S.fromStreamK go
291 -- XXX use cons/nil instead
292 go = K.mkStream $ \_ yld _ stp -> do
293 arr <- liftIO $ readArrayUpto size h
298{-# INLINE_NORMAL readArraysOfUpto #-}
299readArraysOfUpto :: (MonadIO m)
300 => Int -> Handle -> Stream m (Array Word8)
301readArraysOfUpto size h = D.Stream step ()
303 {-# INLINE_LATE step #-}
305 arr <- liftIO $ readArrayUpto size h
311-- XXX read 'Array a' instead of Word8
313-- | @readArrays h@ reads a stream of arrays from file handle @h@.
314-- The maximum size of a single array is limited to @defaultChunkSize@.
315-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
318-- > readArrays = readArraysOfUpto defaultChunkSize
321{-# INLINE readArrays #-}
322readArrays :: (MonadIO m) => Handle -> Stream m (Array Word8)
323readArrays = readArraysOfUpto defaultChunkSize
325-------------------------------------------------------------------------------
326-- Read File to Stream
327-------------------------------------------------------------------------------
329-- TODO for concurrent streams implement readahead IO. We can send multiple
330-- read requests at the same time. For serial case we can use async IO. We can
331-- also control the read throughput in mbps or IOPS.
333-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
334-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
335-- as EOF is encountered.
337{-# INLINE readInChunksOf #-}
338readInChunksOf :: (MonadIO m) => Int -> Handle -> Stream m Word8
339readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
342-- read :: (MonadIO m, Unbox a) => Handle -> Stream m a
344-- > read = 'readByChunks' A.defaultChunkSize
345-- | Generate a stream of elements of the given type from a file 'Handle'. The
346-- stream ends when EOF is encountered.
350read :: (MonadIO m) => Handle -> Stream m Word8
351read = AS.concat . readArrays
353-------------------------------------------------------------------------------
355-------------------------------------------------------------------------------
357-- | Write a stream of arrays to a handle.
360{-# INLINE writeArrays #-}
361writeArrays :: (MonadIO m, Unbox a) => Handle -> Stream m (Array a) -> m ()
362writeArrays h = S.fold (FL.drainMapM (liftIO . writeArray h))
364-- | Write a stream of arrays to a handle after coalescing them in chunks of
365-- specified size. The chunk size is only a maximum and the actual writes could
366-- be smaller than that as we do not split the arrays to fit them to the
370{-# INLINE writeArraysPackedUpto #-}
371writeArraysPackedUpto :: (MonadIO m, Unbox a)
372 => Int -> Handle -> Stream m (Array a) -> m ()
373writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
375#if !defined(mingw32_HOST_OS)
377-- XXX this is incomplete
378-- | Write a stream of 'IOVec' arrays to a handle.
382writev :: MonadIO m => Handle -> Stream m (Array RawIO.IOVec) -> m ()
383writev h = S.mapM_ (liftIO . writeIOVec h)
385-- XXX this is incomplete
386-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
387-- of up to a maximum total size. Writes are performed using gather IO via
388-- @writev@ system call. The maximum number of entries in each 'IOVec' group
392{-# INLINE _writevArraysPackedUpto #-}
393_writevArraysPackedUpto :: MonadIO m
394 => Int -> Handle -> Stream m (Array a) -> m ()
395_writevArraysPackedUpto n h xs =
396 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
400-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
403-- Note that if you use a chunk size less than 8K (GHC's default buffer
404-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
405-- do not want buffering to occur at GHC level as well. Same thing applies to
408-- | Like 'write' but provides control over the write buffer. Output will
409-- be written to the IO device as soon as we collect the specified number of
413{-# INLINE writeInChunksOf #-}
414writeInChunksOf :: MonadIO m => Int -> Handle -> Stream m Word8 -> m ()
415writeInChunksOf n h m = writeArrays h $ AS.chunksOf n m
417-- > write = 'writeInChunksOf' A.defaultChunkSize
419-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
420-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
421-- depends on the 'IOMode' and the current seek position of the handle.
425write :: MonadIO m => Handle -> Stream m Word8 -> m ()
426write = writeInChunksOf defaultChunkSize
430write :: (MonadIO m, Unboxed a) => Handle -> Stream m a -> m ()
431write = toHandleWith A.defaultChunkSize
434-------------------------------------------------------------------------------
435-- IO with encoding/decoding Unicode characters
436-------------------------------------------------------------------------------
440-- > readUtf8 = decodeUtf8 . read
442-- Read a UTF8 encoded stream of unicode characters from a file handle.
445{-# INLINE readUtf8 #-}
446readUtf8 :: (MonadIO m) => Handle -> Stream m Char
447readUtf8 = decodeUtf8 . read
450-- > writeUtf8 h s = write h $ encodeUtf8 s
452-- Encode a stream of unicode characters to UTF8 and write it to the given file
453-- handle. Default block buffering applies to the writes.
456{-# INLINE writeUtf8 #-}
457writeUtf8 :: MonadIO m => Handle -> Stream m Char -> m ()
458writeUtf8 h s = write h $ encodeUtf8 s
460-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
461-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
462-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
463-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
467{-# INLINE writeUtf8ByLines #-}
468writeUtf8ByLines :: (MonadIO m) => Handle -> Stream m Char -> m ()
469writeUtf8ByLines = undefined
471-- | Read UTF-8 lines from a file handle and apply the specified fold to each
472-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
475{-# INLINE readLines #-}
476readLines :: (MonadIO m) => Handle -> Fold m Char b -> Stream m b
477readLines h f = foldLines (readUtf8 h) f
479-------------------------------------------------------------------------------
480-- Framing on a sequence
481-------------------------------------------------------------------------------
483-- | Read a stream from a file handle and split it into frames delimited by
484-- the specified sequence of elements. The supplied fold is applied on each
488{-# INLINE readFrames #-}
489readFrames :: (MonadIO m, Unboxed a)
490 => Array a -> Handle -> Fold m a b -> Stream m b
491readFrames = undefined -- foldFrames . read
493-- | Write a stream to the given file handle buffering up to frames separated
494-- by the given sequence or up to a maximum of @defaultChunkSize@.
497{-# INLINE writeByFrames #-}
498writeByFrames :: (MonadIO m, Unboxed a)
499 => Array a -> Handle -> Stream m a -> m ()
500writeByFrames = undefined
502-------------------------------------------------------------------------------
503-- Random Access IO (Seek)
504-------------------------------------------------------------------------------
506-- XXX handles could be shared, so we may not want to use the handle state at
507-- all for these APIs. we can use pread and pwrite instead. On windows we will
508-- need to use readFile/writeFile with an offset argument.
510-------------------------------------------------------------------------------
512-- | Read the element at the given index treating the file as an array.
515{-# INLINE readIndex #-}
516readIndex :: Unboxed a => Handle -> Int -> Maybe a
517readIndex arr i = undefined
519-- NOTE: To represent a range to read we have chosen (start, size) instead of
520-- (start, end). This helps in removing the ambiguity of whether "end" is
521-- included in the range or not.
523-- We could avoid specifying the range to be read and instead use "take size"
524-- on the stream, but it may end up reading more and then consume it partially.
526-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
527-- from @handle@ starting at the offset @pos@ from the beginning of the file.
529-- Reads are performed in chunks of size @chunkSize@. For block devices, to
530-- avoid reading partial blocks @chunkSize@ must align with the block size of
531-- the underlying device. If the underlying block size is unknown, it is a good
532-- idea to keep it a multiple 4KiB. This API ensures that the start of each
533-- chunk is aligned with @chunkSize@ from second chunk onwards.
535{-# INLINE readSliceWith #-}
536readSliceWith :: (MonadIO m, Unboxed a)
537 => Int -> Handle -> Int -> Int -> Stream m a
538readSliceWith chunkSize h pos len = undefined
540-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
541-- at index @i@ and reading up to @count@ elements in the forward direction
542-- ending at the index @i + count - 1@.
545{-# INLINE readSlice #-}
546readSlice :: (MonadIO m, Unboxed a)
547 => Handle -> Int -> Int -> Stream m a
548readSlice = readSliceWith defaultChunkSize
550-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
551-- at index @i@ and reading up to @count@ elements in the reverse direction
552-- ending at the index @i - count + 1@.
555{-# INLINE readSliceRev #-}
556readSliceRev :: (MonadIO m, Unboxed a)
557 => Handle -> Int -> Int -> Stream m a
558readSliceRev h i count = undefined
560-- | Write the given element at the given index in the file.
563{-# INLINE writeIndex #-}
564writeIndex :: (MonadIO m, Unboxed a) => Handle -> Int -> a -> m ()
565writeIndex h i a = undefined
567-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
568-- starting at index @i@ and writing up to @count@ elements in the forward
569-- direction ending at the index @i + count - 1@.
572{-# INLINE writeSlice #-}
573writeSlice :: (Monad m, Unboxed a)
574 => Handle -> Int -> Int -> Stream m a -> m ()
575writeSlice h i len s = undefined
577-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
578-- starting at index @i@ and writing up to @count@ elements in the reverse
579-- direction ending at the index @i - count + 1@.
582{-# INLINE writeSliceRev #-}
583writeSliceRev :: (Monad m, Unboxed a)
584 => Handle -> Int -> Int -> Stream m a -> m ()
585writeSliceRev 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