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)
123-- import System.IO (Handle, hGetBufSome, hPutBuf)
124import System.IO (IOMode)
125import Prelude hiding (read)
127import qualified GHC.IO.FD as FD
128import qualified GHC.IO.Device as RawIO
130import Streamly.Data.Array (Array, Unbox)
131import Streamly.Data.Stream (Stream)
133import Streamly.Internal.Data.Array (byteLength, unsafeFreeze, unsafePinnedAsPtr)
134import Streamly.Internal.System.IO (defaultChunkSize)
136#if !defined(mingw32_HOST_OS)
138import Streamly.Internal.Data.Stream.IsStream.Type (toStreamD)
139import Streamly.Internal.System.IOVec (groupIOVecsOf)
140import qualified Streamly.Internal.FileSystem.FDIO as RawIO hiding (write)
141import qualified Streamly.Internal.System.IOVec.Type as RawIO
144-- import Streamly.Data.Fold (Fold)
145-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
147import qualified Streamly.Data.Array as A
148import qualified Streamly.Data.Fold as FL
149import qualified Streamly.Internal.Data.MutArray as MArray
150 (MutArray(..), unsafePinnedAsPtr, pinnedNewBytes)
151import qualified Streamly.Internal.Data.Array.Stream as AS
152import qualified Streamly.Internal.Data.Stream as S
153import qualified Streamly.Internal.Data.Stream as D
154 (Stream(..), Step(..))
155import qualified Streamly.Internal.Data.StreamK as K (mkStream)
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 = 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 arr <- MArray.pinnedNewBytes size
222 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
223 MArray.unsafePinnedAsPtr arr $ \p -> do
224 -- n <- hGetBufSome h p size
225#if MIN_VERSION_base(4,15,0)
226 n <- RawIO.read fd p 0 size
228 n <- RawIO.read fd p size
230 -- XXX shrink only if the diff is significant
231 -- Use unsafeFreezeWithShrink
234 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
236-------------------------------------------------------------------------------
238-------------------------------------------------------------------------------
240-- | Write an 'Array' to a file handle.
243{-# INLINABLE writeArray #-}
244writeArray :: Unbox a => Handle -> Array a -> IO ()
245writeArray _ arr | A.length arr == 0 = return ()
246writeArray (Handle fd) arr =
247 unsafePinnedAsPtr arr $ \p ->
248 -- RawIO.writeAll fd (castPtr p) aLen
249#if MIN_VERSION_base(4,15,0)
250 RawIO.write fd (castPtr p) 0 aLen
252 RawIO.write fd (castPtr p) aLen
255 -- Experiment to compare "writev" based IO with "write" based IO.
257 let iov' = iov {arrEnd = arrBound iov}
258 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
259 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
262 aLen = byteLength arr
264#if !defined(mingw32_HOST_OS)
266-- | Write an array of 'IOVec' to a file handle.
269{-# INLINABLE writeIOVec #-}
270writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
271writeIOVec _ iov | A.length iov == 0 = return ()
272writeIOVec (Handle fd) iov =
273 unsafePinnedAsPtr iov $ \p ->
274 RawIO.writevAll fd p (A.length iov)
278-------------------------------------------------------------------------------
279-- Stream of Arrays IO
280-------------------------------------------------------------------------------
282-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
283-- The maximum size of a single array is specified by @size@. The actual size
284-- read may be less than or equal to @size@.
285{-# INLINE _readArraysOfUpto #-}
286_readArraysOfUpto :: (MonadIO m)
287 => Int -> Handle -> Stream m (Array Word8)
288_readArraysOfUpto size h = S.fromStreamK go
290 -- XXX use cons/nil instead
291 go = K.mkStream $ \_ yld _ stp -> do
292 arr <- liftIO $ readArrayUpto size h
297{-# INLINE_NORMAL readArraysOfUpto #-}
298readArraysOfUpto :: (MonadIO m)
299 => Int -> Handle -> Stream m (Array Word8)
300readArraysOfUpto size h = D.Stream step ()
302 {-# INLINE_LATE step #-}
304 arr <- liftIO $ readArrayUpto size h
310-- XXX read 'Array a' instead of Word8
312-- | @readArrays h@ reads a stream of arrays from file handle @h@.
313-- The maximum size of a single array is limited to @defaultChunkSize@.
314-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
317-- > readArrays = readArraysOfUpto defaultChunkSize
320{-# INLINE readArrays #-}
321readArrays :: (MonadIO m) => Handle -> Stream m (Array Word8)
322readArrays = readArraysOfUpto defaultChunkSize
324-------------------------------------------------------------------------------
325-- Read File to Stream
326-------------------------------------------------------------------------------
328-- TODO for concurrent streams implement readahead IO. We can send multiple
329-- read requests at the same time. For serial case we can use async IO. We can
330-- also control the read throughput in mbps or IOPS.
332-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
333-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
334-- as EOF is encountered.
336{-# INLINE readInChunksOf #-}
337readInChunksOf :: (MonadIO m) => Int -> Handle -> Stream m Word8
338readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
341-- read :: (MonadIO m, Unbox a) => Handle -> Stream m a
343-- > read = 'readByChunks' A.defaultChunkSize
344-- | Generate a stream of elements of the given type from a file 'Handle'. The
345-- stream ends when EOF is encountered.
349read :: (MonadIO m) => Handle -> Stream m Word8
350read = AS.concat . readArrays
352-------------------------------------------------------------------------------
354-------------------------------------------------------------------------------
356-- | Write a stream of arrays to a handle.
359{-# INLINE writeArrays #-}
360writeArrays :: (MonadIO m, Unbox a) => Handle -> Stream m (Array a) -> m ()
361writeArrays h = S.fold (FL.drainMapM (liftIO . writeArray h))
363-- | Write a stream of arrays to a handle after coalescing them in chunks of
364-- specified size. The chunk size is only a maximum and the actual writes could
365-- be smaller than that as we do not split the arrays to fit them to the
369{-# INLINE writeArraysPackedUpto #-}
370writeArraysPackedUpto :: (MonadIO m, Unbox a)
371 => Int -> Handle -> Stream m (Array a) -> m ()
372writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
374#if !defined(mingw32_HOST_OS)
376-- XXX this is incomplete
377-- | Write a stream of 'IOVec' arrays to a handle.
381writev :: MonadIO m => Handle -> Stream m (Array RawIO.IOVec) -> m ()
382writev h = S.mapM_ (liftIO . writeIOVec h)
384-- XXX this is incomplete
385-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
386-- of up to a maximum total size. Writes are performed using gather IO via
387-- @writev@ system call. The maximum number of entries in each 'IOVec' group
391{-# INLINE _writevArraysPackedUpto #-}
392_writevArraysPackedUpto :: MonadIO m
393 => Int -> Handle -> Stream m (Array a) -> m ()
394_writevArraysPackedUpto n h xs =
395 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
399-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
402-- Note that if you use a chunk size less than 8K (GHC's default buffer
403-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
404-- do not want buffering to occur at GHC level as well. Same thing applies to
407-- | Like 'write' but provides control over the write buffer. Output will
408-- be written to the IO device as soon as we collect the specified number of
412{-# INLINE writeInChunksOf #-}
413writeInChunksOf :: MonadIO m => Int -> Handle -> Stream m Word8 -> m ()
414writeInChunksOf n h m = writeArrays h $ AS.chunksOf n m
416-- > write = 'writeInChunksOf' A.defaultChunkSize
418-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
419-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
420-- depends on the 'IOMode' and the current seek position of the handle.
424write :: MonadIO m => Handle -> Stream m Word8 -> m ()
425write = writeInChunksOf defaultChunkSize
429write :: (MonadIO m, Unboxed a) => Handle -> Stream m a -> m ()
430write = toHandleWith A.defaultChunkSize
433-------------------------------------------------------------------------------
434-- IO with encoding/decoding Unicode characters
435-------------------------------------------------------------------------------
439-- > readUtf8 = decodeUtf8 . read
441-- Read a UTF8 encoded stream of unicode characters from a file handle.
444{-# INLINE readUtf8 #-}
445readUtf8 :: (MonadIO m) => Handle -> Stream m Char
446readUtf8 = decodeUtf8 . read
449-- > writeUtf8 h s = write h $ encodeUtf8 s
451-- Encode a stream of unicode characters to UTF8 and write it to the given file
452-- handle. Default block buffering applies to the writes.
455{-# INLINE writeUtf8 #-}
456writeUtf8 :: MonadIO m => Handle -> Stream m Char -> m ()
457writeUtf8 h s = write h $ encodeUtf8 s
459-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
460-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
461-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
462-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
466{-# INLINE writeUtf8ByLines #-}
467writeUtf8ByLines :: (MonadIO m) => Handle -> Stream m Char -> m ()
468writeUtf8ByLines = undefined
470-- | Read UTF-8 lines from a file handle and apply the specified fold to each
471-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
474{-# INLINE readLines #-}
475readLines :: (MonadIO m) => Handle -> Fold m Char b -> Stream m b
476readLines h f = foldLines (readUtf8 h) f
478-------------------------------------------------------------------------------
479-- Framing on a sequence
480-------------------------------------------------------------------------------
482-- | Read a stream from a file handle and split it into frames delimited by
483-- the specified sequence of elements. The supplied fold is applied on each
487{-# INLINE readFrames #-}
488readFrames :: (MonadIO m, Unboxed a)
489 => Array a -> Handle -> Fold m a b -> Stream m b
490readFrames = undefined -- foldFrames . read
492-- | Write a stream to the given file handle buffering up to frames separated
493-- by the given sequence or up to a maximum of @defaultChunkSize@.
496{-# INLINE writeByFrames #-}
497writeByFrames :: (MonadIO m, Unboxed a)
498 => Array a -> Handle -> Stream m a -> m ()
499writeByFrames = undefined
501-------------------------------------------------------------------------------
502-- Random Access IO (Seek)
503-------------------------------------------------------------------------------
505-- XXX handles could be shared, so we may not want to use the handle state at
506-- all for these APIs. we can use pread and pwrite instead. On windows we will
507-- need to use readFile/writeFile with an offset argument.
509-------------------------------------------------------------------------------
511-- | Read the element at the given index treating the file as an array.
514{-# INLINE readIndex #-}
515readIndex :: Unboxed a => Handle -> Int -> Maybe a
516readIndex arr i = undefined
518-- NOTE: To represent a range to read we have chosen (start, size) instead of
519-- (start, end). This helps in removing the ambiguity of whether "end" is
520-- included in the range or not.
522-- We could avoid specifying the range to be read and instead use "take size"
523-- on the stream, but it may end up reading more and then consume it partially.
525-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
526-- from @handle@ starting at the offset @pos@ from the beginning of the file.
528-- Reads are performed in chunks of size @chunkSize@. For block devices, to
529-- avoid reading partial blocks @chunkSize@ must align with the block size of
530-- the underlying device. If the underlying block size is unknown, it is a good
531-- idea to keep it a multiple 4KiB. This API ensures that the start of each
532-- chunk is aligned with @chunkSize@ from second chunk onwards.
534{-# INLINE readSliceWith #-}
535readSliceWith :: (MonadIO m, Unboxed a)
536 => Int -> Handle -> Int -> Int -> Stream m a
537readSliceWith chunkSize h pos len = undefined
539-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
540-- at index @i@ and reading up to @count@ elements in the forward direction
541-- ending at the index @i + count - 1@.
544{-# INLINE readSlice #-}
545readSlice :: (MonadIO m, Unboxed a)
546 => Handle -> Int -> Int -> Stream m a
547readSlice = readSliceWith defaultChunkSize
549-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
550-- at index @i@ and reading up to @count@ elements in the reverse direction
551-- ending at the index @i - count + 1@.
554{-# INLINE readSliceRev #-}
555readSliceRev :: (MonadIO m, Unboxed a)
556 => Handle -> Int -> Int -> Stream m a
557readSliceRev h i count = undefined
559-- | Write the given element at the given index in the file.
562{-# INLINE writeIndex #-}
563writeIndex :: (MonadIO m, Unboxed a) => Handle -> Int -> a -> m ()
564writeIndex h i a = undefined
566-- | @writeSlice 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 forward
568-- direction ending at the index @i + count - 1@.
571{-# INLINE writeSlice #-}
572writeSlice :: (Monad m, Unboxed a)
573 => Handle -> Int -> Int -> Stream m a -> m ()
574writeSlice h i len s = undefined
576-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
577-- starting at index @i@ and writing up to @count@ elements in the reverse
578-- direction ending at the index @i - count + 1@.
581{-# INLINE writeSliceRev #-}
582writeSliceRev :: (Monad m, Unboxed a)
583 => Handle -> Int -> Int -> Stream m a -> m ()
584writeSliceRev 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