on 3fd33b6 help sign in
583 lines 21 kB history raw
1#include "inline.hs"
3-- |
4-- Module : Streamly.Internal.FileSystem.FD
5-- Copyright : (c) 2019 Composewell Technologies
6--
7-- License : BSD3
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
10-- Portability : GHC
11--
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.
16--
17-- Read and write data as streams and arrays to and from files.
18--
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'.
25--
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
30-- arrays.
31--
32-- > import qualified Streamly.Internal.FileSystem.FD as FD
33--
35module Streamly.Internal.FileSystem.FD
36 (
37 -- * File Handles
38 Handle
39 , stdin
40 , stdout
41 , stderr
42 , openFile
44 -- TODO file path based APIs
45 -- , readFile
46 -- , writeFile
48 -- * Streaming IO
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
65 -- access capability.
67 -- ** Read File to Stream
68 , read
69 -- , readUtf8
70 -- , readLines
71 -- , readFrames
72 , readInChunksOf
74 -- -- * Array Read
75 -- , readArrayUpto
76 -- , readArrayOf
78 , readArrays
79 , readArraysOfUpto
80 -- , readArraysOf
82 -- ** Write File from Stream
83 , write
84 -- , writeUtf8
85 -- , writeUtf8Lines
86 -- , writeFrames
87 , writeInChunksOf
89 -- -- * Array Write
90 -- , writeArray
91 , writeArrays
92 , writeArraysPackedUpto
94 -- XXX these are incomplete
95 -- , writev
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.
103 --
104 -- , readIndex
105 -- , readSlice
106 -- , readSliceRev
107 -- , readAt -- read from a given position to th end of file
108 -- , readSliceArrayUpto
109 -- , readSliceArrayOf
111 -- , writeIndex
112 -- , writeSlice
113 -- , writeSliceRev
114 -- , writeAt -- start writing at the given position
115 -- , writeSliceArray
116 )
117where
119import Control.Monad.IO.Class (MonadIO(..))
120import Data.Word (Word8)
121-- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
122import Foreign.Ptr (castPtr)
123import Streamly.Internal.Data.Unboxed (Unboxed)
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.Internal.Data.Array.Unboxed.Type
132 (Array(..), byteLength, unsafeFreeze, asPtrUnsafe)
133import Streamly.Internal.System.IO (defaultChunkSize)
134import Streamly.Internal.Data.Stream.Type (Stream)
135import Streamly.Internal.Data.Stream.IsStream.Type
136 (IsStream, mkStream, fromStreamD)
137#if !defined(mingw32_HOST_OS)
138{-
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
143-}
144#endif
145-- import Streamly.Data.Fold (Fold)
146-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
148import qualified Streamly.Data.Array.Unboxed as A
149import qualified Streamly.Internal.Data.Array.Unboxed.Mut as MArray
150 (Array(..), newPinnedArrayBytes, asPtrUnsafe)
151import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
152import qualified Streamly.Prelude as S
153import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
154 (Stream(..), Step(..))
156-------------------------------------------------------------------------------
157-- References
158-------------------------------------------------------------------------------
159--
160-- The following references may be useful to build an understanding about the
161-- file API design:
162--
163-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
164-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
165-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
166-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
167-- https://www.w3.org/TR/FileAPI/ for http file API.
169-------------------------------------------------------------------------------
170-- Handles
171-------------------------------------------------------------------------------
173-- XXX attach a finalizer
174-- | A 'Handle' is returned by 'openFile' and is subsequently used to perform
175-- read and write operations on a file.
176--
177newtype Handle = Handle FD.FD
179-- | File handle for standard input
180stdin :: Handle
181stdin = Handle FD.stdin
183-- | File handle for standard output
184stdout :: Handle
185stdout = Handle FD.stdout
187-- | File handle for standard error
188stderr :: Handle
189stderr = Handle FD.stderr
191-- XXX we can support all the flags that the "open" system call supports.
192-- Instead of using RTS locking mechanism can we use system provided locking
193-- instead?
194--
195-- | Open a file that is not a directory and return a file handle.
196-- 'openFile' enforces a multiple-reader single-writer locking on files. That
197-- is, there may either be many handles on the same file which manage input, or
198-- just one handle on the file which manages output. If any open handle is
199-- managing a file for output, no new handle can be allocated for that file. If
200-- any open handle is managing a file for input, new handles can only be
201-- allocated if they do not manage output. Whether two files are the same is
202-- implementation-dependent, but they should normally be the same if they have
203-- the same absolute path name and neither has been renamed, for example.
204--
205openFile :: FilePath -> IOMode -> IO Handle
206openFile path mode = Handle . fst <$> FD.openFile path mode True
208-------------------------------------------------------------------------------
209-- Array IO (Input)
210-------------------------------------------------------------------------------
212-- | Read a 'ByteArray' from a file handle. If no data is available on the
213-- handle it blocks until some data becomes available. If data is available
214-- then it immediately returns that data without blocking. It reads a maximum
215-- of up to the size requested.
216{-# INLINABLE readArrayUpto #-}
217readArrayUpto :: Int -> Handle -> IO (Array Word8)
218readArrayUpto size (Handle fd) = do
219 arr <- MArray.newPinnedArrayBytes size
220 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
221 MArray.asPtrUnsafe arr $ \p -> do
222 -- n <- hGetBufSome h p size
223#if MIN_VERSION_base(4,15,0)
224 n <- RawIO.read fd p 0 size
225#else
226 n <- RawIO.read fd p size
227#endif
228 -- XXX shrink only if the diff is significant
229 -- Use unsafeFreezeWithShrink
230 return
231 $ unsafeFreeze
232 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
234-------------------------------------------------------------------------------
235-- Array IO (output)
236-------------------------------------------------------------------------------
238-- | Write an 'Array' to a file handle.
239--
240-- @since 0.7.0
241{-# INLINABLE writeArray #-}
242writeArray :: Unboxed a => Handle -> Array a -> IO ()
243writeArray _ arr | A.length arr == 0 = return ()
244writeArray (Handle fd) arr =
245 asPtrUnsafe arr $ \p ->
246 -- RawIO.writeAll fd (castPtr p) aLen
247#if MIN_VERSION_base(4,15,0)
248 RawIO.write fd (castPtr p) 0 aLen
249#else
250 RawIO.write fd (castPtr p) aLen
251#endif
252 {-
253 -- Experiment to compare "writev" based IO with "write" based IO.
254 iov <- A.newArray 1
255 let iov' = iov {arrEnd = arrBound iov}
256 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
257 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
258 -}
259 where
260 aLen = byteLength arr
262#if !defined(mingw32_HOST_OS)
263{-
264-- | Write an array of 'IOVec' to a file handle.
265--
266-- @since 0.7.0
267{-# INLINABLE writeIOVec #-}
268writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
269writeIOVec _ iov | A.length iov == 0 = return ()
270writeIOVec (Handle fd) iov =
271 asPtrUnsafe iov $ \p ->
272 RawIO.writevAll fd p (A.length iov)
273-}
274#endif
276-------------------------------------------------------------------------------
277-- Stream of Arrays IO
278-------------------------------------------------------------------------------
280-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
281-- The maximum size of a single array is specified by @size@. The actual size
282-- read may be less than or equal to @size@.
283{-# INLINE _readArraysOfUpto #-}
284_readArraysOfUpto :: (IsStream t, MonadIO m)
285 => Int -> Handle -> t m (Array Word8)
286_readArraysOfUpto size h = go
287 where
288 -- XXX use cons/nil instead
289 go = mkStream $ \_ yld _ stp -> do
290 arr <- liftIO $ readArrayUpto size h
291 if A.length arr == 0
292 then stp
293 else yld arr go
295{-# INLINE_NORMAL readArraysOfUpto #-}
296readArraysOfUpto :: (IsStream t, MonadIO m)
297 => Int -> Handle -> t m (Array Word8)
298readArraysOfUpto size h = fromStreamD (D.Stream step ())
299 where
300 {-# INLINE_LATE step #-}
301 step _ _ = do
302 arr <- liftIO $ readArrayUpto size h
303 return $
304 case A.length arr of
305 0 -> D.Stop
306 _ -> D.Yield arr ()
308-- XXX read 'Array a' instead of Word8
309--
310-- | @readArrays h@ reads a stream of arrays from file handle @h@.
311-- The maximum size of a single array is limited to @defaultChunkSize@.
312-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
313-- on the 'Handle'.
314--
315-- > readArrays = readArraysOfUpto defaultChunkSize
316--
317-- @since 0.7.0
318{-# INLINE readArrays #-}
319readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
320readArrays = readArraysOfUpto defaultChunkSize
322-------------------------------------------------------------------------------
323-- Read File to Stream
324-------------------------------------------------------------------------------
326-- TODO for concurrent streams implement readahead IO. We can send multiple
327-- read requests at the same time. For serial case we can use async IO. We can
328-- also control the read throughput in mbps or IOPS.
330-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
331-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
332-- as EOF is encountered.
333--
334{-# INLINE readInChunksOf #-}
335readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
336readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
338-- TODO
339-- read :: (IsStream t, MonadIO m, Unboxed a) => Handle -> t m a
340--
341-- > read = 'readByChunks' A.defaultChunkSize
342-- | Generate a stream of elements of the given type from a file 'Handle'. The
343-- stream ends when EOF is encountered.
344--
345-- @since 0.7.0
346{-# INLINE read #-}
347read :: (IsStream t, MonadIO m) => Handle -> t m Word8
348read = AS.concat . readArrays
350-------------------------------------------------------------------------------
351-- Writing
352-------------------------------------------------------------------------------
354-- | Write a stream of arrays to a handle.
355--
356-- @since 0.7.0
357{-# INLINE writeArrays #-}
358writeArrays :: (MonadIO m, Unboxed a) => Handle -> Stream m (Array a) -> m ()
359writeArrays h = S.mapM_ (liftIO . writeArray h)
361-- | Write a stream of arrays to a handle after coalescing them in chunks of
362-- specified size. The chunk size is only a maximum and the actual writes could
363-- be smaller than that as we do not split the arrays to fit them to the
364-- specified size.
365--
366-- @since 0.7.0
367{-# INLINE writeArraysPackedUpto #-}
368writeArraysPackedUpto :: (MonadIO m, Unboxed a)
369 => Int -> Handle -> Stream m (Array a) -> m ()
370writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
372#if !defined(mingw32_HOST_OS)
373{-
374-- XXX this is incomplete
375-- | Write a stream of 'IOVec' arrays to a handle.
376--
377-- @since 0.7.0
378{-# INLINE writev #-}
379writev :: MonadIO m => Handle -> Stream m (Array RawIO.IOVec) -> m ()
380writev h = S.mapM_ (liftIO . writeIOVec h)
382-- XXX this is incomplete
383-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
384-- of up to a maximum total size. Writes are performed using gather IO via
385-- @writev@ system call. The maximum number of entries in each 'IOVec' group
386-- limited to 512.
387--
388-- @since 0.7.0
389{-# INLINE _writevArraysPackedUpto #-}
390_writevArraysPackedUpto :: MonadIO m
391 => Int -> Handle -> Stream m (Array a) -> m ()
392_writevArraysPackedUpto n h xs =
393 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
394-}
395#endif
397-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
398--
399-- XXX test this
400-- Note that if you use a chunk size less than 8K (GHC's default buffer
401-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
402-- do not want buffering to occur at GHC level as well. Same thing applies to
403-- writes as well.
405-- | Like 'write' but provides control over the write buffer. Output will
406-- be written to the IO device as soon as we collect the specified number of
407-- input elements.
408--
409-- @since 0.7.0
410{-# INLINE writeInChunksOf #-}
411writeInChunksOf :: MonadIO m => Int -> Handle -> Stream m Word8 -> m ()
412writeInChunksOf n h m = writeArrays h $ AS.arraysOf n m
414-- > write = 'writeInChunksOf' A.defaultChunkSize
415--
416-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
417-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
418-- depends on the 'IOMode' and the current seek position of the handle.
419--
420-- @since 0.7.0
421{-# INLINE write #-}
422write :: MonadIO m => Handle -> Stream m Word8 -> m ()
423write = writeInChunksOf defaultChunkSize
425{-
426{-# INLINE write #-}
427write :: (MonadIO m, Unboxed a) => Handle -> Stream m a -> m ()
428write = toHandleWith A.defaultChunkSize
429-}
431-------------------------------------------------------------------------------
432-- IO with encoding/decoding Unicode characters
433-------------------------------------------------------------------------------
435{-
436-- |
437-- > readUtf8 = decodeUtf8 . read
438--
439-- Read a UTF8 encoded stream of unicode characters from a file handle.
440--
441-- @since 0.7.0
442{-# INLINE readUtf8 #-}
443readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
444readUtf8 = decodeUtf8 . read
446-- |
447-- > writeUtf8 h s = write h $ encodeUtf8 s
448--
449-- Encode a stream of unicode characters to UTF8 and write it to the given file
450-- handle. Default block buffering applies to the writes.
451--
452-- @since 0.7.0
453{-# INLINE writeUtf8 #-}
454writeUtf8 :: MonadIO m => Handle -> Stream m Char -> m ()
455writeUtf8 h s = write h $ encodeUtf8 s
457-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
458-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
459-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
460-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
461-- option.
462--
463-- @since 0.7.0
464{-# INLINE writeUtf8ByLines #-}
465writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
466writeUtf8ByLines = undefined
468-- | Read UTF-8 lines from a file handle and apply the specified fold to each
469-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
470--
471-- @since 0.7.0
472{-# INLINE readLines #-}
473readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
474readLines h f = foldLines (readUtf8 h) f
476-------------------------------------------------------------------------------
477-- Framing on a sequence
478-------------------------------------------------------------------------------
480-- | Read a stream from a file handle and split it into frames delimited by
481-- the specified sequence of elements. The supplied fold is applied on each
482-- frame.
483--
484-- @since 0.7.0
485{-# INLINE readFrames #-}
486readFrames :: (IsStream t, MonadIO m, Unboxed a)
487 => Array a -> Handle -> Fold m a b -> t m b
488readFrames = undefined -- foldFrames . read
490-- | Write a stream to the given file handle buffering up to frames separated
491-- by the given sequence or up to a maximum of @defaultChunkSize@.
492--
493-- @since 0.7.0
494{-# INLINE writeByFrames #-}
495writeByFrames :: (IsStream t, MonadIO m, Unboxed a)
496 => Array a -> Handle -> t m a -> m ()
497writeByFrames = undefined
499-------------------------------------------------------------------------------
500-- Random Access IO (Seek)
501-------------------------------------------------------------------------------
503-- XXX handles could be shared, so we may not want to use the handle state at
504-- all for these APIs. we can use pread and pwrite instead. On windows we will
505-- need to use readFile/writeFile with an offset argument.
507-------------------------------------------------------------------------------
509-- | Read the element at the given index treating the file as an array.
510--
511-- @since 0.7.0
512{-# INLINE readIndex #-}
513readIndex :: Unboxed a => Handle -> Int -> Maybe a
514readIndex arr i = undefined
516-- NOTE: To represent a range to read we have chosen (start, size) instead of
517-- (start, end). This helps in removing the ambiguity of whether "end" is
518-- included in the range or not.
519--
520-- We could avoid specifying the range to be read and instead use "take size"
521-- on the stream, but it may end up reading more and then consume it partially.
523-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
524-- from @handle@ starting at the offset @pos@ from the beginning of the file.
525--
526-- Reads are performed in chunks of size @chunkSize@. For block devices, to
527-- avoid reading partial blocks @chunkSize@ must align with the block size of
528-- the underlying device. If the underlying block size is unknown, it is a good
529-- idea to keep it a multiple 4KiB. This API ensures that the start of each
530-- chunk is aligned with @chunkSize@ from second chunk onwards.
531--
532{-# INLINE readSliceWith #-}
533readSliceWith :: (IsStream t, MonadIO m, Unboxed a)
534 => Int -> Handle -> Int -> Int -> t m a
535readSliceWith chunkSize h pos len = undefined
537-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
538-- at index @i@ and reading up to @count@ elements in the forward direction
539-- ending at the index @i + count - 1@.
540--
541-- @since 0.7.0
542{-# INLINE readSlice #-}
543readSlice :: (IsStream t, MonadIO m, Unboxed a)
544 => Handle -> Int -> Int -> t m a
545readSlice = readSliceWith defaultChunkSize
547-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
548-- at index @i@ and reading up to @count@ elements in the reverse direction
549-- ending at the index @i - count + 1@.
550--
551-- @since 0.7.0
552{-# INLINE readSliceRev #-}
553readSliceRev :: (IsStream t, MonadIO m, Unboxed a)
554 => Handle -> Int -> Int -> t m a
555readSliceRev h i count = undefined
557-- | Write the given element at the given index in the file.
558--
559-- @since 0.7.0
560{-# INLINE writeIndex #-}
561writeIndex :: (MonadIO m, Unboxed a) => Handle -> Int -> a -> m ()
562writeIndex h i a = undefined
564-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
565-- starting at index @i@ and writing up to @count@ elements in the forward
566-- direction ending at the index @i + count - 1@.
567--
568-- @since 0.7.0
569{-# INLINE writeSlice #-}
570writeSlice :: (IsStream t, Monad m, Unboxed a)
571 => Handle -> Int -> Int -> t m a -> m ()
572writeSlice h i len s = undefined
574-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
575-- starting at index @i@ and writing up to @count@ elements in the reverse
576-- direction ending at the index @i - count + 1@.
577--
578-- @since 0.7.0
579{-# INLINE writeSliceRev #-}
580writeSliceRev :: (IsStream t, Monad m, Unboxed a)
581 => Handle -> Int -> Int -> t m a -> m ()
582writeSliceRev arr i len s = undefined
583-}