on master help sign in
585 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)
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)
137{-
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
142-}
143#endif
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-------------------------------------------------------------------------------
159-- References
160-------------------------------------------------------------------------------
161--
162-- The following references may be useful to build an understanding about the
163-- file API design:
164--
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-------------------------------------------------------------------------------
172-- Handles
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.
178--
179newtype Handle = Handle FD.FD
181-- | File handle for standard input
182stdin :: Handle
183stdin = Handle FD.stdin
185-- | File handle for standard output
186stdout :: Handle
187stdout = Handle FD.stdout
189-- | File handle for standard error
190stderr :: Handle
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
195-- instead?
196--
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.
206--
207openFile :: FilePath -> IOMode -> IO Handle
208openFile path mode = Handle . fst <$> FD.openFile path mode True
210-------------------------------------------------------------------------------
211-- Array IO (Input)
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
227#else
228 n <- RawIO.read fd p size
229#endif
230 -- XXX shrink only if the diff is significant
231 -- Use unsafeFreezeWithShrink
232 return
233 $ unsafeFreeze
234 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
236-------------------------------------------------------------------------------
237-- Array IO (output)
238-------------------------------------------------------------------------------
240-- | Write an 'Array' to a file handle.
241--
242-- @since 0.7.0
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
251#else
252 RawIO.write fd (castPtr p) aLen
253#endif
254 {-
255 -- Experiment to compare "writev" based IO with "write" based IO.
256 iov <- A.newArray 1
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
260 -}
261 where
262 aLen = byteLength arr
264#if !defined(mingw32_HOST_OS)
265{-
266-- | Write an array of 'IOVec' to a file handle.
267--
268-- @since 0.7.0
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)
275-}
276#endif
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
289 where
290 -- XXX use cons/nil instead
291 go = K.mkStream $ \_ yld _ stp -> do
292 arr <- liftIO $ readArrayUpto size h
293 if A.length arr == 0
294 then stp
295 else yld arr go
297{-# INLINE_NORMAL readArraysOfUpto #-}
298readArraysOfUpto :: (MonadIO m)
299 => Int -> Handle -> Stream m (Array Word8)
300readArraysOfUpto size h = D.Stream step ()
301 where
302 {-# INLINE_LATE step #-}
303 step _ _ = do
304 arr <- liftIO $ readArrayUpto size h
305 return $
306 case A.length arr of
307 0 -> D.Stop
308 _ -> D.Yield arr ()
310-- XXX read 'Array a' instead of Word8
311--
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'
315-- on the 'Handle'.
316--
317-- > readArrays = readArraysOfUpto defaultChunkSize
318--
319-- @since 0.7.0
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.
335--
336{-# INLINE readInChunksOf #-}
337readInChunksOf :: (MonadIO m) => Int -> Handle -> Stream m Word8
338readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
340-- TODO
341-- read :: (MonadIO m, Unbox a) => Handle -> Stream m a
342--
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.
346--
347-- @since 0.7.0
348{-# INLINE read #-}
349read :: (MonadIO m) => Handle -> Stream m Word8
350read = AS.concat . readArrays
352-------------------------------------------------------------------------------
353-- Writing
354-------------------------------------------------------------------------------
356-- | Write a stream of arrays to a handle.
357--
358-- @since 0.7.0
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
366-- specified size.
367--
368-- @since 0.7.0
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)
375{-
376-- XXX this is incomplete
377-- | Write a stream of 'IOVec' arrays to a handle.
378--
379-- @since 0.7.0
380{-# INLINE writev #-}
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
388-- limited to 512.
389--
390-- @since 0.7.0
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)
396-}
397#endif
399-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
400--
401-- XXX test this
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
405-- writes as well.
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
409-- input elements.
410--
411-- @since 0.7.0
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
417--
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.
421--
422-- @since 0.7.0
423{-# INLINE write #-}
424write :: MonadIO m => Handle -> Stream m Word8 -> m ()
425write = writeInChunksOf defaultChunkSize
427{-
428{-# INLINE write #-}
429write :: (MonadIO m, Unboxed a) => Handle -> Stream m a -> m ()
430write = toHandleWith A.defaultChunkSize
431-}
433-------------------------------------------------------------------------------
434-- IO with encoding/decoding Unicode characters
435-------------------------------------------------------------------------------
437{-
438-- |
439-- > readUtf8 = decodeUtf8 . read
440--
441-- Read a UTF8 encoded stream of unicode characters from a file handle.
442--
443-- @since 0.7.0
444{-# INLINE readUtf8 #-}
445readUtf8 :: (MonadIO m) => Handle -> Stream m Char
446readUtf8 = decodeUtf8 . read
448-- |
449-- > writeUtf8 h s = write h $ encodeUtf8 s
450--
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.
453--
454-- @since 0.7.0
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'
463-- option.
464--
465-- @since 0.7.0
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.
472--
473-- @since 0.7.0
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
484-- frame.
485--
486-- @since 0.7.0
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@.
494--
495-- @since 0.7.0
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.
512--
513-- @since 0.7.0
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.
521--
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.
527--
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.
533--
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@.
542--
543-- @since 0.7.0
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@.
552--
553-- @since 0.7.0
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.
560--
561-- @since 0.7.0
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@.
569--
570-- @since 0.7.0
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@.
579--
580-- @since 0.7.0
581{-# INLINE writeSliceRev #-}
582writeSliceRev :: (Monad m, Unboxed a)
583 => Handle -> Int -> Int -> Stream m a -> m ()
584writeSliceRev arr i len s = undefined
585-}