on 233ea77 help sign in
570 lines 21 kB history raw
1{-# LANGUAGE CPP #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.FileSystem.FD
7-- Copyright : (c) 2019 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
14-- This module is a an experimental replacement for
15-- "Streamly.FileSystem.Handle". The former module provides IO facilities based
16-- on the GHC Handle type. The APIs in this module avoid the GHC handle layer
17-- and provide more explicit control over buffering.
18--
19-- Read and write data as streams and arrays to and from files.
20--
21-- This module provides read and write APIs based on handles. Before reading or
22-- writing, a file must be opened first using 'openFile'. The 'Handle' returned
23-- by 'openFile' is then used to access the file. A 'Handle' is backed by an
24-- operating system file descriptor. When the 'Handle' is garbage collected the
25-- underlying file descriptor is automatically closed. A handle can be
26-- explicitly closed using 'closeFile'.
27--
28-- Reading and writing APIs are divided into two categories, sequential
29-- streaming APIs and random or seekable access APIs. File IO APIs are quite
30-- similar to "Streamly.Memory.Array" read write APIs. In that regard, arrays can
31-- be considered as in-memory files or files can be considered as on-disk
32-- arrays.
33--
34-- > import qualified Streamly.FileSystem.FD as FD
35--
37module Streamly.FileSystem.FD
38 (
39 -- * File Handles
40 Handle
41 , stdin
42 , stdout
43 , stderr
44 , openFile
46 -- TODO file path based APIs
47 -- , readFile
48 -- , writeFile
50 -- * Streaming IO
51 -- | Streaming APIs read or write data to or from a file or device
52 -- sequentially, they never perform a seek to a random location. When
53 -- reading, the stream is lazy and generated on-demand as the consumer
54 -- consumes it. Read IO requests to the IO device are performed in chunks
55 -- of 32KiB, this is referred to as @defaultChunkSize@ in the
56 -- documentation. One IO request may or may not read the full chunk. If the
57 -- whole stream is not consumed, it is possible that we may read slightly
58 -- more from the IO device than what the consumer needed. Unless specified
59 -- otherwise in the API, writes are collected into chunks of
60 -- @defaultChunkSize@ before they are written to the IO device.
62 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
63 -- including disks, files, memory devices, terminals, pipes, sockets and
64 -- fifos. While random access APIs work only for files or devices that have
65 -- random access or seek capability for example disks, memory devices.
66 -- Devices like terminals, pipes, sockets and fifos do not have random
67 -- access capability.
69 -- ** Read File to Stream
70 , read
71 -- , readUtf8
72 -- , readLines
73 -- , readFrames
74 , readInChunksOf
76 -- -- * Array Read
77 -- , readArrayUpto
78 -- , readArrayOf
80 , readArrays
81 , readArraysOfUpto
82 -- , readArraysOf
84 -- ** Write File from Stream
85 , write
86 -- , writeUtf8
87 -- , writeUtf8Lines
88 -- , writeFrames
89 , writeInChunksOf
91 -- -- * Array Write
92 -- , writeArray
93 , writeArrays
94 , writeArraysPackedUpto
96 -- XXX these are incomplete
97 -- , writev
98 -- , writevArraysPackedUpto
100 -- -- * Random Access (Seek)
101 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
102 -- files that have random access or seek capability. This type of devices
103 -- include disks, files, memory devices and exclude terminals, pipes,
104 -- sockets and fifos.
105 --
106 -- , readIndex
107 -- , readSlice
108 -- , readSliceRev
109 -- , readAt -- read from a given position to th end of file
110 -- , readSliceArrayUpto
111 -- , readSliceArrayOf
113 -- , writeIndex
114 -- , writeSlice
115 -- , writeSliceRev
116 -- , writeAt -- start writing at the given position
117 -- , writeSliceArray
118 )
119where
121import Control.Monad.IO.Class (MonadIO(..))
122import Data.Word (Word8)
123import Foreign.ForeignPtr (withForeignPtr)
124-- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
125import Foreign.Ptr (plusPtr, castPtr)
126import Foreign.Storable (Storable(..))
127import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
128-- import System.IO (Handle, hGetBufSome, hPutBuf)
129import System.IO (IOMode)
130import Prelude hiding (read)
132import qualified GHC.IO.FD as FD
133import qualified GHC.IO.Device as RawIO
135import Streamly.Internal.Memory.Array.Types (Array(..), byteLength, defaultChunkSize)
136import Streamly.Internal.Data.Stream.Serial (SerialT)
137import Streamly.Internal.Data.Stream.StreamK.Type (IsStream, mkStream)
139#if !defined(mingw32_HOST_OS)
140import Streamly.Internal.Memory.Array.Types (groupIOVecsOf)
141import Streamly.Internal.Data.Stream.StreamD (toStreamD)
142import Streamly.Internal.Data.Stream.StreamD.Type (fromStreamD)
143import qualified Streamly.FileSystem.FDIO as RawIO hiding (write)
144#endif
145-- import Streamly.Data.Fold (Fold)
146-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
148import qualified Streamly.Memory.Array as A
149import qualified Streamly.Internal.Memory.ArrayStream as AS
150import qualified Streamly.Prelude as S
151import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
153-------------------------------------------------------------------------------
154-- References
155-------------------------------------------------------------------------------
156--
157-- The following references may be useful to build an understanding about the
158-- file API design:
159--
160-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
161-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
162-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
163-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
164-- https://www.w3.org/TR/FileAPI/ for http file API.
166-------------------------------------------------------------------------------
167-- Handles
168-------------------------------------------------------------------------------
170-- XXX attach a finalizer
171-- | A 'Handle' is returned by 'openFile' and is subsequently used to perform
172-- read and write operations on a file.
173--
174newtype Handle = Handle FD.FD
176-- | File handle for standard input
177stdin :: Handle
178stdin = Handle FD.stdin
180-- | File handle for standard output
181stdout :: Handle
182stdout = Handle FD.stdout
184-- | File handle for standard error
185stderr :: Handle
186stderr = Handle FD.stderr
188-- XXX we can support all the flags that the "open" system call supports.
189-- Instead of using RTS locking mechanism can we use system provided locking
190-- instead?
191--
192-- | Open a file that is not a directory and return a file handle.
193-- 'openFile' enforces a multiple-reader single-writer locking on files. That
194-- is, there may either be many handles on the same file which manage input, or
195-- just one handle on the file which manages output. If any open handle is
196-- managing a file for output, no new handle can be allocated for that file. If
197-- any open handle is managing a file for input, new handles can only be
198-- allocated if they do not manage output. Whether two files are the same is
199-- implementation-dependent, but they should normally be the same if they have
200-- the same absolute path name and neither has been renamed, for example.
201--
202openFile :: FilePath -> IOMode -> IO Handle
203openFile path mode = Handle . fst <$> FD.openFile path mode True
205-------------------------------------------------------------------------------
206-- Array IO (Input)
207-------------------------------------------------------------------------------
209-- | Read a 'ByteArray' from a file handle. If no data is available on the
210-- handle it blocks until some data becomes available. If data is available
211-- then it immediately returns that data without blocking. It reads a maximum
212-- of up to the size requested.
213{-# INLINABLE readArrayUpto #-}
214readArrayUpto :: Int -> Handle -> IO (Array Word8)
215readArrayUpto size (Handle fd) = do
216 ptr <- mallocPlainForeignPtrBytes size
217 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
218 withForeignPtr ptr $ \p -> do
219 -- n <- hGetBufSome h p size
220 n <- RawIO.read fd p size
221 let v = Array
222 { aStart = ptr
223 , aEnd = p `plusPtr` n
224 , aBound = p `plusPtr` size
225 }
226 -- XXX shrink only if the diff is significant
227 -- A.shrinkToFit v
228 return v
230-------------------------------------------------------------------------------
231-- Array IO (output)
232-------------------------------------------------------------------------------
234-- | Write an 'Array' to a file handle.
235--
236-- @since 0.7.0
237{-# INLINABLE writeArray #-}
238writeArray :: Storable a => Handle -> Array a -> IO ()
239writeArray _ arr | A.length arr == 0 = return ()
240writeArray (Handle fd) arr = withForeignPtr (aStart arr) $ \p ->
241 -- RawIO.writeAll fd (castPtr p) aLen
242 RawIO.write fd (castPtr p) aLen
243 {-
244 -- Experiment to compare "writev" based IO with "write" based IO.
245 iov <- A.newArray 1
246 let iov' = iov {aEnd = aBound iov}
247 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
248 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
249 -}
250 where
251 aLen = byteLength arr
253#if !defined(mingw32_HOST_OS)
254-- | Write an array of 'IOVec' to a file handle.
255--
256-- @since 0.7.0
257{-# INLINABLE writeIOVec #-}
258writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
259writeIOVec _ iov | A.length iov == 0 = return ()
260writeIOVec (Handle fd) iov =
261 withForeignPtr (aStart iov) $ \p ->
262 RawIO.writevAll fd p (A.length iov)
263#endif
265-------------------------------------------------------------------------------
266-- Stream of Arrays IO
267-------------------------------------------------------------------------------
269-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
270-- The maximum size of a single array is specified by @size@. The actual size
271-- read may be less than or equal to @size@.
272{-# INLINABLE _readArraysOfUpto #-}
273_readArraysOfUpto :: (IsStream t, MonadIO m)
274 => Int -> Handle -> t m (Array Word8)
275_readArraysOfUpto size h = go
276 where
277 -- XXX use cons/nil instead
278 go = mkStream $ \_ yld _ stp -> do
279 arr <- liftIO $ readArrayUpto size h
280 if A.length arr == 0
281 then stp
282 else yld arr go
284{-# INLINE_NORMAL readArraysOfUpto #-}
285readArraysOfUpto :: (IsStream t, MonadIO m)
286 => Int -> Handle -> t m (Array Word8)
287readArraysOfUpto size h = D.fromStreamD (D.Stream step ())
288 where
289 {-# INLINE_LATE step #-}
290 step _ _ = do
291 arr <- liftIO $ readArrayUpto size h
292 return $
293 case A.length arr of
294 0 -> D.Stop
295 _ -> D.Yield arr ()
297-- XXX read 'Array a' instead of Word8
298--
299-- | @readArrays h@ reads a stream of arrays from file handle @h@.
300-- The maximum size of a single array is limited to @defaultChunkSize@.
301-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
302-- on the 'Handle'.
303--
304-- > readArrays = readArraysOfUpto defaultChunkSize
305--
306-- @since 0.7.0
307{-# INLINE readArrays #-}
308readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
309readArrays = readArraysOfUpto defaultChunkSize
311-------------------------------------------------------------------------------
312-- Read File to Stream
313-------------------------------------------------------------------------------
315-- TODO for concurrent streams implement readahead IO. We can send multiple
316-- read requests at the same time. For serial case we can use async IO. We can
317-- also control the read throughput in mbps or IOPS.
319-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
320-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
321-- as EOF is encountered.
322--
323{-# INLINE readInChunksOf #-}
324readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
325readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
327-- TODO
328-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
329--
330-- > read = 'readByChunks' A.defaultChunkSize
331-- | Generate a stream of elements of the given type from a file 'Handle'. The
332-- stream ends when EOF is encountered.
333--
334-- @since 0.7.0
335{-# INLINE read #-}
336read :: (IsStream t, MonadIO m) => Handle -> t m Word8
337read = AS.concat . readArrays
339-------------------------------------------------------------------------------
340-- Writing
341-------------------------------------------------------------------------------
343-- | Write a stream of arrays to a handle.
344--
345-- @since 0.7.0
346{-# INLINE writeArrays #-}
347writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
348writeArrays h = S.mapM_ (liftIO . writeArray h)
350-- | Write a stream of arrays to a handle after coalescing them in chunks of
351-- specified size. The chunk size is only a maximum and the actual writes could
352-- be smaller than that as we do not split the arrays to fit them to the
353-- specified size.
354--
355-- @since 0.7.0
356{-# INLINE writeArraysPackedUpto #-}
357writeArraysPackedUpto :: (MonadIO m, Storable a)
358 => Int -> Handle -> SerialT m (Array a) -> m ()
359writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
361#if !defined(mingw32_HOST_OS)
362-- XXX this is incomplete
363-- | Write a stream of 'IOVec' arrays to a handle.
364--
365-- @since 0.7.0
366{-# INLINE writev #-}
367writev :: MonadIO m => Handle -> SerialT m (Array RawIO.IOVec) -> m ()
368writev h = S.mapM_ (liftIO . writeIOVec h)
370-- XXX this is incomplete
371-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
372-- of up to a maximum total size. Writes are performed using gather IO via
373-- @writev@ system call. The maximum number of entries in each 'IOVec' group
374-- limited to 512.
375--
376-- @since 0.7.0
377{-# INLINE _writevArraysPackedUpto #-}
378_writevArraysPackedUpto :: MonadIO m
379 => Int -> Handle -> SerialT m (Array a) -> m ()
380_writevArraysPackedUpto n h xs =
381 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
382#endif
384-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
385--
386-- XXX test this
387-- Note that if you use a chunk size less than 8K (GHC's default buffer
388-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
389-- do not want buffering to occur at GHC level as well. Same thing applies to
390-- writes as well.
392-- | Like 'write' but provides control over the write buffer. Output will
393-- be written to the IO device as soon as we collect the specified number of
394-- input elements.
395--
396-- @since 0.7.0
397{-# INLINE writeInChunksOf #-}
398writeInChunksOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
399writeInChunksOf n h m = writeArrays h $ AS.arraysOf n m
401-- > write = 'writeInChunksOf' A.defaultChunkSize
402--
403-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
404-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
405-- depends on the 'IOMode' and the current seek position of the handle.
406--
407-- @since 0.7.0
408{-# INLINE write #-}
409write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
410write = writeInChunksOf defaultChunkSize
412{-
413{-# INLINE write #-}
414write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
415write = toHandleWith A.defaultChunkSize
416-}
418-------------------------------------------------------------------------------
419-- IO with encoding/decoding Unicode characters
420-------------------------------------------------------------------------------
422{-
423-- |
424-- > readUtf8 = decodeUtf8 . read
425--
426-- Read a UTF8 encoded stream of unicode characters from a file handle.
427--
428-- @since 0.7.0
429{-# INLINE readUtf8 #-}
430readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
431readUtf8 = decodeUtf8 . read
433-- |
434-- > writeUtf8 h s = write h $ encodeUtf8 s
435--
436-- Encode a stream of unicode characters to UTF8 and write it to the given file
437-- handle. Default block buffering applies to the writes.
438--
439-- @since 0.7.0
440{-# INLINE writeUtf8 #-}
441writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
442writeUtf8 h s = write h $ encodeUtf8 s
444-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
445-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
446-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
447-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
448-- option.
449--
450-- @since 0.7.0
451{-# INLINE writeUtf8ByLines #-}
452writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
453writeUtf8ByLines = undefined
455-- | Read UTF-8 lines from a file handle and apply the specified fold to each
456-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
457--
458-- @since 0.7.0
459{-# INLINE readLines #-}
460readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
461readLines h f = foldLines (readUtf8 h) f
463-------------------------------------------------------------------------------
464-- Framing on a sequence
465-------------------------------------------------------------------------------
467-- | Read a stream from a file handle and split it into frames delimited by
468-- the specified sequence of elements. The supplied fold is applied on each
469-- frame.
470--
471-- @since 0.7.0
472{-# INLINE readFrames #-}
473readFrames :: (IsStream t, MonadIO m, Storable a)
474 => Array a -> Handle -> Fold m a b -> t m b
475readFrames = undefined -- foldFrames . read
477-- | Write a stream to the given file handle buffering up to frames separated
478-- by the given sequence or up to a maximum of @defaultChunkSize@.
479--
480-- @since 0.7.0
481{-# INLINE writeByFrames #-}
482writeByFrames :: (IsStream t, MonadIO m, Storable a)
483 => Array a -> Handle -> t m a -> m ()
484writeByFrames = undefined
486-------------------------------------------------------------------------------
487-- Random Access IO (Seek)
488-------------------------------------------------------------------------------
490-- XXX handles could be shared, so we may not want to use the handle state at
491-- all for these APIs. we can use pread and pwrite instead. On windows we will
492-- need to use readFile/writeFile with an offset argument.
494-------------------------------------------------------------------------------
496-- | Read the element at the given index treating the file as an array.
497--
498-- @since 0.7.0
499{-# INLINE readIndex #-}
500readIndex :: Storable a => Handle -> Int -> Maybe a
501readIndex arr i = undefined
503-- NOTE: To represent a range to read we have chosen (start, size) instead of
504-- (start, end). This helps in removing the ambiguity of whether "end" is
505-- included in the range or not.
506--
507-- We could avoid specifying the range to be read and instead use "take size"
508-- on the stream, but it may end up reading more and then consume it partially.
510-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
511-- from @handle@ starting at the offset @pos@ from the beginning of the file.
512--
513-- Reads are performed in chunks of size @chunkSize@. For block devices, to
514-- avoid reading partial blocks @chunkSize@ must align with the block size of
515-- the underlying device. If the underlying block size is unknown, it is a good
516-- idea to keep it a multiple 4KiB. This API ensures that the start of each
517-- chunk is aligned with @chunkSize@ from second chunk onwards.
518--
519{-# INLINE readSliceWith #-}
520readSliceWith :: (IsStream t, MonadIO m, Storable a)
521 => Int -> Handle -> Int -> Int -> t m a
522readSliceWith chunkSize h pos len = undefined
524-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
525-- at index @i@ and reading up to @count@ elements in the forward direction
526-- ending at the index @i + count - 1@.
527--
528-- @since 0.7.0
529{-# INLINE readSlice #-}
530readSlice :: (IsStream t, MonadIO m, Storable a)
531 => Handle -> Int -> Int -> t m a
532readSlice = readSliceWith defaultChunkSize
534-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
535-- at index @i@ and reading up to @count@ elements in the reverse direction
536-- ending at the index @i - count + 1@.
537--
538-- @since 0.7.0
539{-# INLINE readSliceRev #-}
540readSliceRev :: (IsStream t, MonadIO m, Storable a)
541 => Handle -> Int -> Int -> t m a
542readSliceRev h i count = undefined
544-- | Write the given element at the given index in the file.
545--
546-- @since 0.7.0
547{-# INLINE writeIndex #-}
548writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
549writeIndex h i a = undefined
551-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
552-- starting at index @i@ and writing up to @count@ elements in the forward
553-- direction ending at the index @i + count - 1@.
554--
555-- @since 0.7.0
556{-# INLINE writeSlice #-}
557writeSlice :: (IsStream t, Monad m, Storable a)
558 => Handle -> Int -> Int -> t m a -> m ()
559writeSlice h i len s = undefined
561-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
562-- starting at index @i@ and writing up to @count@ elements in the reverse
563-- direction ending at the index @i - count + 1@.
564--
565-- @since 0.7.0
566{-# INLINE writeSliceRev #-}
567writeSliceRev :: (IsStream t, Monad m, Storable a)
568 => Handle -> Int -> Int -> t m a -> m ()
569writeSliceRev arr i len s = undefined
570-}