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)
121import Foreign.ForeignPtr (withForeignPtr)
122-- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
123import Foreign.Ptr (plusPtr, castPtr)
124import Foreign.Storable (Storable(..))
125import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
126-- import System.IO (Handle, hGetBufSome, hPutBuf)
127import System.IO (IOMode)
128import Prelude hiding (read)
130import qualified GHC.IO.FD as FD
131import qualified GHC.IO.Device as RawIO
133import Streamly.Internal.Data.Array.Foreign.Type
134 (Array(..), byteLength, unsafeFreeze)
135import Streamly.Internal.Data.Array.Foreign.Mut.Type (fromForeignPtrUnsafe)
136import Streamly.Internal.System.IO (defaultChunkSize)
137import Streamly.Internal.Data.Stream.Serial (SerialT)
138import Streamly.Internal.Data.Stream.IsStream.Type
139 (IsStream, mkStream, fromStreamD)
140#if !defined(mingw32_HOST_OS)
141import Streamly.Internal.Data.Stream.IsStream.Type (toStreamD)
142import Streamly.Internal.System.IOVec (groupIOVecsOf)
143import qualified Streamly.Internal.FileSystem.FDIO as RawIO hiding (write)
144import qualified Streamly.Internal.System.IOVec.Type as RawIO
146-- import Streamly.Data.Fold (Fold)
147-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
149import qualified Streamly.Data.Array.Foreign as A
150import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
151import qualified Streamly.Prelude as S
152import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
154-------------------------------------------------------------------------------
156-------------------------------------------------------------------------------
158-- The following references may be useful to build an understanding about the
161-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
162-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
163-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
164-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
165-- https://www.w3.org/TR/FileAPI/ for http file API.
167-------------------------------------------------------------------------------
169-------------------------------------------------------------------------------
171-- XXX attach a finalizer
172-- | A 'Handle' is returned by 'openFile' and is subsequently used to perform
173-- read and write operations on a file.
175newtype Handle = Handle FD.FD
177-- | File handle for standard input
179stdin = Handle FD.stdin
181-- | File handle for standard output
183stdout = Handle FD.stdout
185-- | File handle for standard error
187stderr = Handle FD.stderr
189-- XXX we can support all the flags that the "open" system call supports.
190-- Instead of using RTS locking mechanism can we use system provided locking
193-- | Open a file that is not a directory and return a file handle.
194-- 'openFile' enforces a multiple-reader single-writer locking on files. That
195-- is, there may either be many handles on the same file which manage input, or
196-- just one handle on the file which manages output. If any open handle is
197-- managing a file for output, no new handle can be allocated for that file. If
198-- any open handle is managing a file for input, new handles can only be
199-- allocated if they do not manage output. Whether two files are the same is
200-- implementation-dependent, but they should normally be the same if they have
201-- the same absolute path name and neither has been renamed, for example.
203openFile :: FilePath -> IOMode -> IO Handle
204openFile path mode = Handle . fst <$> FD.openFile path mode True
206-------------------------------------------------------------------------------
208-------------------------------------------------------------------------------
210-- | Read a 'ByteArray' from a file handle. If no data is available on the
211-- handle it blocks until some data becomes available. If data is available
212-- then it immediately returns that data without blocking. It reads a maximum
213-- of up to the size requested.
214{-# INLINABLE readArrayUpto #-}
215readArrayUpto :: Int -> Handle -> IO (Array Word8)
216readArrayUpto size (Handle fd) = do
217 ptr <- mallocPlainForeignPtrBytes size
218 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
219 withForeignPtr ptr $ \p -> do
220 -- n <- hGetBufSome h p size
221#if MIN_VERSION_base(4,15,0)
222 n <- RawIO.read fd p 0 size
224 n <- RawIO.read fd p size
226 -- XXX shrink only if the diff is significant
227 -- Use unsafeFreezeWithShrink
230 $ fromForeignPtrUnsafe ptr (p `plusPtr` n) (p `plusPtr` size)
232-------------------------------------------------------------------------------
234-------------------------------------------------------------------------------
236-- | Write an 'Array' to a file handle.
239{-# INLINABLE writeArray #-}
240writeArray :: Storable a => Handle -> Array a -> IO ()
241writeArray _ arr | A.length arr == 0 = return ()
242writeArray (Handle fd) arr = withForeignPtr (aStart arr) $ \p ->
243 -- RawIO.writeAll fd (castPtr p) aLen
244#if MIN_VERSION_base(4,15,0)
245 RawIO.write fd (castPtr p) 0 aLen
247 RawIO.write fd (castPtr p) aLen
250 -- Experiment to compare "writev" based IO with "write" based IO.
252 let iov' = iov {aEnd = aBound iov}
253 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
254 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
257 aLen = byteLength arr
259#if !defined(mingw32_HOST_OS)
260-- | Write an array of 'IOVec' to a file handle.
263{-# INLINABLE writeIOVec #-}
264writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
265writeIOVec _ iov | A.length iov == 0 = return ()
266writeIOVec (Handle fd) iov =
267 withForeignPtr (aStart iov) $ \p ->
268 RawIO.writevAll fd p (A.length iov)
271-------------------------------------------------------------------------------
272-- Stream of Arrays IO
273-------------------------------------------------------------------------------
275-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
276-- The maximum size of a single array is specified by @size@. The actual size
277-- read may be less than or equal to @size@.
278{-# INLINABLE _readArraysOfUpto #-}
279_readArraysOfUpto :: (IsStream t, MonadIO m)
280 => Int -> Handle -> t m (Array Word8)
281_readArraysOfUpto size h = go
283 -- XXX use cons/nil instead
284 go = mkStream $ \_ yld _ stp -> do
285 arr <- liftIO $ readArrayUpto size h
290{-# INLINE_NORMAL readArraysOfUpto #-}
291readArraysOfUpto :: (IsStream t, MonadIO m)
292 => Int -> Handle -> t m (Array Word8)
293readArraysOfUpto size h = fromStreamD (D.Stream step ())
295 {-# INLINE_LATE step #-}
297 arr <- liftIO $ readArrayUpto size h
303-- XXX read 'Array a' instead of Word8
305-- | @readArrays h@ reads a stream of arrays from file handle @h@.
306-- The maximum size of a single array is limited to @defaultChunkSize@.
307-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
310-- > readArrays = readArraysOfUpto defaultChunkSize
313{-# INLINE readArrays #-}
314readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
315readArrays = readArraysOfUpto defaultChunkSize
317-------------------------------------------------------------------------------
318-- Read File to Stream
319-------------------------------------------------------------------------------
321-- TODO for concurrent streams implement readahead IO. We can send multiple
322-- read requests at the same time. For serial case we can use async IO. We can
323-- also control the read throughput in mbps or IOPS.
325-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
326-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
327-- as EOF is encountered.
329{-# INLINE readInChunksOf #-}
330readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
331readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
334-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
336-- > read = 'readByChunks' A.defaultChunkSize
337-- | Generate a stream of elements of the given type from a file 'Handle'. The
338-- stream ends when EOF is encountered.
342read :: (IsStream t, MonadIO m) => Handle -> t m Word8
343read = AS.concat . readArrays
345-------------------------------------------------------------------------------
347-------------------------------------------------------------------------------
349-- | Write a stream of arrays to a handle.
352{-# INLINE writeArrays #-}
353writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
354writeArrays h = S.mapM_ (liftIO . writeArray h)
356-- | Write a stream of arrays to a handle after coalescing them in chunks of
357-- specified size. The chunk size is only a maximum and the actual writes could
358-- be smaller than that as we do not split the arrays to fit them to the
362{-# INLINE writeArraysPackedUpto #-}
363writeArraysPackedUpto :: (MonadIO m, Storable a)
364 => Int -> Handle -> SerialT m (Array a) -> m ()
365writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
367#if !defined(mingw32_HOST_OS)
368-- XXX this is incomplete
369-- | Write a stream of 'IOVec' arrays to a handle.
373writev :: MonadIO m => Handle -> SerialT m (Array RawIO.IOVec) -> m ()
374writev h = S.mapM_ (liftIO . writeIOVec h)
376-- XXX this is incomplete
377-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
378-- of up to a maximum total size. Writes are performed using gather IO via
379-- @writev@ system call. The maximum number of entries in each 'IOVec' group
383{-# INLINE _writevArraysPackedUpto #-}
384_writevArraysPackedUpto :: MonadIO m
385 => Int -> Handle -> SerialT m (Array a) -> m ()
386_writevArraysPackedUpto n h xs =
387 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
390-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
393-- Note that if you use a chunk size less than 8K (GHC's default buffer
394-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
395-- do not want buffering to occur at GHC level as well. Same thing applies to
398-- | Like 'write' but provides control over the write buffer. Output will
399-- be written to the IO device as soon as we collect the specified number of
403{-# INLINE writeInChunksOf #-}
404writeInChunksOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
405writeInChunksOf n h m = writeArrays h $ AS.arraysOf n m
407-- > write = 'writeInChunksOf' A.defaultChunkSize
409-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
410-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
411-- depends on the 'IOMode' and the current seek position of the handle.
415write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
416write = writeInChunksOf defaultChunkSize
420write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
421write = toHandleWith A.defaultChunkSize
424-------------------------------------------------------------------------------
425-- IO with encoding/decoding Unicode characters
426-------------------------------------------------------------------------------
430-- > readUtf8 = decodeUtf8 . read
432-- Read a UTF8 encoded stream of unicode characters from a file handle.
435{-# INLINE readUtf8 #-}
436readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
437readUtf8 = decodeUtf8 . read
440-- > writeUtf8 h s = write h $ encodeUtf8 s
442-- Encode a stream of unicode characters to UTF8 and write it to the given file
443-- handle. Default block buffering applies to the writes.
446{-# INLINE writeUtf8 #-}
447writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
448writeUtf8 h s = write h $ encodeUtf8 s
450-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
451-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
452-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
453-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
457{-# INLINE writeUtf8ByLines #-}
458writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
459writeUtf8ByLines = undefined
461-- | Read UTF-8 lines from a file handle and apply the specified fold to each
462-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
465{-# INLINE readLines #-}
466readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
467readLines h f = foldLines (readUtf8 h) f
469-------------------------------------------------------------------------------
470-- Framing on a sequence
471-------------------------------------------------------------------------------
473-- | Read a stream from a file handle and split it into frames delimited by
474-- the specified sequence of elements. The supplied fold is applied on each
478{-# INLINE readFrames #-}
479readFrames :: (IsStream t, MonadIO m, Storable a)
480 => Array a -> Handle -> Fold m a b -> t m b
481readFrames = undefined -- foldFrames . read
483-- | Write a stream to the given file handle buffering up to frames separated
484-- by the given sequence or up to a maximum of @defaultChunkSize@.
487{-# INLINE writeByFrames #-}
488writeByFrames :: (IsStream t, MonadIO m, Storable a)
489 => Array a -> Handle -> t m a -> m ()
490writeByFrames = undefined
492-------------------------------------------------------------------------------
493-- Random Access IO (Seek)
494-------------------------------------------------------------------------------
496-- XXX handles could be shared, so we may not want to use the handle state at
497-- all for these APIs. we can use pread and pwrite instead. On windows we will
498-- need to use readFile/writeFile with an offset argument.
500-------------------------------------------------------------------------------
502-- | Read the element at the given index treating the file as an array.
505{-# INLINE readIndex #-}
506readIndex :: Storable a => Handle -> Int -> Maybe a
507readIndex arr i = undefined
509-- NOTE: To represent a range to read we have chosen (start, size) instead of
510-- (start, end). This helps in removing the ambiguity of whether "end" is
511-- included in the range or not.
513-- We could avoid specifying the range to be read and instead use "take size"
514-- on the stream, but it may end up reading more and then consume it partially.
516-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
517-- from @handle@ starting at the offset @pos@ from the beginning of the file.
519-- Reads are performed in chunks of size @chunkSize@. For block devices, to
520-- avoid reading partial blocks @chunkSize@ must align with the block size of
521-- the underlying device. If the underlying block size is unknown, it is a good
522-- idea to keep it a multiple 4KiB. This API ensures that the start of each
523-- chunk is aligned with @chunkSize@ from second chunk onwards.
525{-# INLINE readSliceWith #-}
526readSliceWith :: (IsStream t, MonadIO m, Storable a)
527 => Int -> Handle -> Int -> Int -> t m a
528readSliceWith chunkSize h pos len = undefined
530-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
531-- at index @i@ and reading up to @count@ elements in the forward direction
532-- ending at the index @i + count - 1@.
535{-# INLINE readSlice #-}
536readSlice :: (IsStream t, MonadIO m, Storable a)
537 => Handle -> Int -> Int -> t m a
538readSlice = readSliceWith defaultChunkSize
540-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
541-- at index @i@ and reading up to @count@ elements in the reverse direction
542-- ending at the index @i - count + 1@.
545{-# INLINE readSliceRev #-}
546readSliceRev :: (IsStream t, MonadIO m, Storable a)
547 => Handle -> Int -> Int -> t m a
548readSliceRev h i count = undefined
550-- | Write the given element at the given index in the file.
553{-# INLINE writeIndex #-}
554writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
555writeIndex h i a = undefined
557-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
558-- starting at index @i@ and writing up to @count@ elements in the forward
559-- direction ending at the index @i + count - 1@.
562{-# INLINE writeSlice #-}
563writeSlice :: (IsStream t, Monad m, Storable a)
564 => Handle -> Int -> Int -> t m a -> m ()
565writeSlice h i len s = undefined
567-- | @writeSliceRev 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 reverse
569-- direction ending at the index @i - count + 1@.
572{-# INLINE writeSliceRev #-}
573writeSliceRev :: (IsStream t, Monad m, Storable a)
574 => Handle -> Int -> Int -> t m a -> m ()
575writeSliceRev 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