on 09f2fa7 help sign in
568 lines 21 kB history raw
1#include "inline.hs"
3-- |
4-- Module : Streamly.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.Memory.Array" 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.FileSystem.FD as FD
33--
35module Streamly.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)
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.Memory.Array.Types (Array(..), byteLength, defaultChunkSize)
134import Streamly.Internal.Data.Stream.Serial (SerialT)
135import Streamly.Internal.Data.Stream.StreamK.Type (IsStream, mkStream)
137#if !defined(mingw32_HOST_OS)
138import Streamly.Internal.Memory.Array.Types (groupIOVecsOf)
139import Streamly.Internal.Data.Stream.StreamD (toStreamD)
140import Streamly.Internal.Data.Stream.StreamD.Type (fromStreamD)
141import qualified Streamly.FileSystem.FDIO as RawIO hiding (write)
142#endif
143-- import Streamly.Data.Fold (Fold)
144-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
146import qualified Streamly.Memory.Array as A
147import qualified Streamly.Internal.Memory.ArrayStream as AS
148import qualified Streamly.Prelude as S
149import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
151-------------------------------------------------------------------------------
152-- References
153-------------------------------------------------------------------------------
154--
155-- The following references may be useful to build an understanding about the
156-- file API design:
157--
158-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
159-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
160-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
161-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
162-- https://www.w3.org/TR/FileAPI/ for http file API.
164-------------------------------------------------------------------------------
165-- Handles
166-------------------------------------------------------------------------------
168-- XXX attach a finalizer
169-- | A 'Handle' is returned by 'openFile' and is subsequently used to perform
170-- read and write operations on a file.
171--
172newtype Handle = Handle FD.FD
174-- | File handle for standard input
175stdin :: Handle
176stdin = Handle FD.stdin
178-- | File handle for standard output
179stdout :: Handle
180stdout = Handle FD.stdout
182-- | File handle for standard error
183stderr :: Handle
184stderr = Handle FD.stderr
186-- XXX we can support all the flags that the "open" system call supports.
187-- Instead of using RTS locking mechanism can we use system provided locking
188-- instead?
189--
190-- | Open a file that is not a directory and return a file handle.
191-- 'openFile' enforces a multiple-reader single-writer locking on files. That
192-- is, there may either be many handles on the same file which manage input, or
193-- just one handle on the file which manages output. If any open handle is
194-- managing a file for output, no new handle can be allocated for that file. If
195-- any open handle is managing a file for input, new handles can only be
196-- allocated if they do not manage output. Whether two files are the same is
197-- implementation-dependent, but they should normally be the same if they have
198-- the same absolute path name and neither has been renamed, for example.
199--
200openFile :: FilePath -> IOMode -> IO Handle
201openFile path mode = Handle . fst <$> FD.openFile path mode True
203-------------------------------------------------------------------------------
204-- Array IO (Input)
205-------------------------------------------------------------------------------
207-- | Read a 'ByteArray' from a file handle. If no data is available on the
208-- handle it blocks until some data becomes available. If data is available
209-- then it immediately returns that data without blocking. It reads a maximum
210-- of up to the size requested.
211{-# INLINABLE readArrayUpto #-}
212readArrayUpto :: Int -> Handle -> IO (Array Word8)
213readArrayUpto size (Handle fd) = do
214 ptr <- mallocPlainForeignPtrBytes size
215 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
216 withForeignPtr ptr $ \p -> do
217 -- n <- hGetBufSome h p size
218 n <- RawIO.read fd p size
219 let v = Array
220 { aStart = ptr
221 , aEnd = p `plusPtr` n
222 , aBound = p `plusPtr` size
223 }
224 -- XXX shrink only if the diff is significant
225 -- A.shrinkToFit v
226 return v
228-------------------------------------------------------------------------------
229-- Array IO (output)
230-------------------------------------------------------------------------------
232-- | Write an 'Array' to a file handle.
233--
234-- @since 0.7.0
235{-# INLINABLE writeArray #-}
236writeArray :: Storable a => Handle -> Array a -> IO ()
237writeArray _ arr | A.length arr == 0 = return ()
238writeArray (Handle fd) arr = withForeignPtr (aStart arr) $ \p ->
239 -- RawIO.writeAll fd (castPtr p) aLen
240 RawIO.write fd (castPtr p) aLen
241 {-
242 -- Experiment to compare "writev" based IO with "write" based IO.
243 iov <- A.newArray 1
244 let iov' = iov {aEnd = aBound iov}
245 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
246 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
247 -}
248 where
249 aLen = byteLength arr
251#if !defined(mingw32_HOST_OS)
252-- | Write an array of 'IOVec' to a file handle.
253--
254-- @since 0.7.0
255{-# INLINABLE writeIOVec #-}
256writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
257writeIOVec _ iov | A.length iov == 0 = return ()
258writeIOVec (Handle fd) iov =
259 withForeignPtr (aStart iov) $ \p ->
260 RawIO.writevAll fd p (A.length iov)
261#endif
263-------------------------------------------------------------------------------
264-- Stream of Arrays IO
265-------------------------------------------------------------------------------
267-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
268-- The maximum size of a single array is specified by @size@. The actual size
269-- read may be less than or equal to @size@.
270{-# INLINABLE _readArraysOfUpto #-}
271_readArraysOfUpto :: (IsStream t, MonadIO m)
272 => Int -> Handle -> t m (Array Word8)
273_readArraysOfUpto size h = go
274 where
275 -- XXX use cons/nil instead
276 go = mkStream $ \_ yld _ stp -> do
277 arr <- liftIO $ readArrayUpto size h
278 if A.length arr == 0
279 then stp
280 else yld arr go
282{-# INLINE_NORMAL readArraysOfUpto #-}
283readArraysOfUpto :: (IsStream t, MonadIO m)
284 => Int -> Handle -> t m (Array Word8)
285readArraysOfUpto size h = D.fromStreamD (D.Stream step ())
286 where
287 {-# INLINE_LATE step #-}
288 step _ _ = do
289 arr <- liftIO $ readArrayUpto size h
290 return $
291 case A.length arr of
292 0 -> D.Stop
293 _ -> D.Yield arr ()
295-- XXX read 'Array a' instead of Word8
296--
297-- | @readArrays h@ reads a stream of arrays from file handle @h@.
298-- The maximum size of a single array is limited to @defaultChunkSize@.
299-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
300-- on the 'Handle'.
301--
302-- > readArrays = readArraysOfUpto defaultChunkSize
303--
304-- @since 0.7.0
305{-# INLINE readArrays #-}
306readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
307readArrays = readArraysOfUpto defaultChunkSize
309-------------------------------------------------------------------------------
310-- Read File to Stream
311-------------------------------------------------------------------------------
313-- TODO for concurrent streams implement readahead IO. We can send multiple
314-- read requests at the same time. For serial case we can use async IO. We can
315-- also control the read throughput in mbps or IOPS.
317-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
318-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
319-- as EOF is encountered.
320--
321{-# INLINE readInChunksOf #-}
322readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
323readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
325-- TODO
326-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
327--
328-- > read = 'readByChunks' A.defaultChunkSize
329-- | Generate a stream of elements of the given type from a file 'Handle'. The
330-- stream ends when EOF is encountered.
331--
332-- @since 0.7.0
333{-# INLINE read #-}
334read :: (IsStream t, MonadIO m) => Handle -> t m Word8
335read = AS.concat . readArrays
337-------------------------------------------------------------------------------
338-- Writing
339-------------------------------------------------------------------------------
341-- | Write a stream of arrays to a handle.
342--
343-- @since 0.7.0
344{-# INLINE writeArrays #-}
345writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
346writeArrays h = S.mapM_ (liftIO . writeArray h)
348-- | Write a stream of arrays to a handle after coalescing them in chunks of
349-- specified size. The chunk size is only a maximum and the actual writes could
350-- be smaller than that as we do not split the arrays to fit them to the
351-- specified size.
352--
353-- @since 0.7.0
354{-# INLINE writeArraysPackedUpto #-}
355writeArraysPackedUpto :: (MonadIO m, Storable a)
356 => Int -> Handle -> SerialT m (Array a) -> m ()
357writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
359#if !defined(mingw32_HOST_OS)
360-- XXX this is incomplete
361-- | Write a stream of 'IOVec' arrays to a handle.
362--
363-- @since 0.7.0
364{-# INLINE writev #-}
365writev :: MonadIO m => Handle -> SerialT m (Array RawIO.IOVec) -> m ()
366writev h = S.mapM_ (liftIO . writeIOVec h)
368-- XXX this is incomplete
369-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
370-- of up to a maximum total size. Writes are performed using gather IO via
371-- @writev@ system call. The maximum number of entries in each 'IOVec' group
372-- limited to 512.
373--
374-- @since 0.7.0
375{-# INLINE _writevArraysPackedUpto #-}
376_writevArraysPackedUpto :: MonadIO m
377 => Int -> Handle -> SerialT m (Array a) -> m ()
378_writevArraysPackedUpto n h xs =
379 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
380#endif
382-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
383--
384-- XXX test this
385-- Note that if you use a chunk size less than 8K (GHC's default buffer
386-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
387-- do not want buffering to occur at GHC level as well. Same thing applies to
388-- writes as well.
390-- | Like 'write' but provides control over the write buffer. Output will
391-- be written to the IO device as soon as we collect the specified number of
392-- input elements.
393--
394-- @since 0.7.0
395{-# INLINE writeInChunksOf #-}
396writeInChunksOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
397writeInChunksOf n h m = writeArrays h $ AS.arraysOf n m
399-- > write = 'writeInChunksOf' A.defaultChunkSize
400--
401-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
402-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
403-- depends on the 'IOMode' and the current seek position of the handle.
404--
405-- @since 0.7.0
406{-# INLINE write #-}
407write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
408write = writeInChunksOf defaultChunkSize
410{-
411{-# INLINE write #-}
412write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
413write = toHandleWith A.defaultChunkSize
414-}
416-------------------------------------------------------------------------------
417-- IO with encoding/decoding Unicode characters
418-------------------------------------------------------------------------------
420{-
421-- |
422-- > readUtf8 = decodeUtf8 . read
423--
424-- Read a UTF8 encoded stream of unicode characters from a file handle.
425--
426-- @since 0.7.0
427{-# INLINE readUtf8 #-}
428readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
429readUtf8 = decodeUtf8 . read
431-- |
432-- > writeUtf8 h s = write h $ encodeUtf8 s
433--
434-- Encode a stream of unicode characters to UTF8 and write it to the given file
435-- handle. Default block buffering applies to the writes.
436--
437-- @since 0.7.0
438{-# INLINE writeUtf8 #-}
439writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
440writeUtf8 h s = write h $ encodeUtf8 s
442-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
443-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
444-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
445-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
446-- option.
447--
448-- @since 0.7.0
449{-# INLINE writeUtf8ByLines #-}
450writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
451writeUtf8ByLines = undefined
453-- | Read UTF-8 lines from a file handle and apply the specified fold to each
454-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
455--
456-- @since 0.7.0
457{-# INLINE readLines #-}
458readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
459readLines h f = foldLines (readUtf8 h) f
461-------------------------------------------------------------------------------
462-- Framing on a sequence
463-------------------------------------------------------------------------------
465-- | Read a stream from a file handle and split it into frames delimited by
466-- the specified sequence of elements. The supplied fold is applied on each
467-- frame.
468--
469-- @since 0.7.0
470{-# INLINE readFrames #-}
471readFrames :: (IsStream t, MonadIO m, Storable a)
472 => Array a -> Handle -> Fold m a b -> t m b
473readFrames = undefined -- foldFrames . read
475-- | Write a stream to the given file handle buffering up to frames separated
476-- by the given sequence or up to a maximum of @defaultChunkSize@.
477--
478-- @since 0.7.0
479{-# INLINE writeByFrames #-}
480writeByFrames :: (IsStream t, MonadIO m, Storable a)
481 => Array a -> Handle -> t m a -> m ()
482writeByFrames = undefined
484-------------------------------------------------------------------------------
485-- Random Access IO (Seek)
486-------------------------------------------------------------------------------
488-- XXX handles could be shared, so we may not want to use the handle state at
489-- all for these APIs. we can use pread and pwrite instead. On windows we will
490-- need to use readFile/writeFile with an offset argument.
492-------------------------------------------------------------------------------
494-- | Read the element at the given index treating the file as an array.
495--
496-- @since 0.7.0
497{-# INLINE readIndex #-}
498readIndex :: Storable a => Handle -> Int -> Maybe a
499readIndex arr i = undefined
501-- NOTE: To represent a range to read we have chosen (start, size) instead of
502-- (start, end). This helps in removing the ambiguity of whether "end" is
503-- included in the range or not.
504--
505-- We could avoid specifying the range to be read and instead use "take size"
506-- on the stream, but it may end up reading more and then consume it partially.
508-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
509-- from @handle@ starting at the offset @pos@ from the beginning of the file.
510--
511-- Reads are performed in chunks of size @chunkSize@. For block devices, to
512-- avoid reading partial blocks @chunkSize@ must align with the block size of
513-- the underlying device. If the underlying block size is unknown, it is a good
514-- idea to keep it a multiple 4KiB. This API ensures that the start of each
515-- chunk is aligned with @chunkSize@ from second chunk onwards.
516--
517{-# INLINE readSliceWith #-}
518readSliceWith :: (IsStream t, MonadIO m, Storable a)
519 => Int -> Handle -> Int -> Int -> t m a
520readSliceWith chunkSize h pos len = undefined
522-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
523-- at index @i@ and reading up to @count@ elements in the forward direction
524-- ending at the index @i + count - 1@.
525--
526-- @since 0.7.0
527{-# INLINE readSlice #-}
528readSlice :: (IsStream t, MonadIO m, Storable a)
529 => Handle -> Int -> Int -> t m a
530readSlice = readSliceWith defaultChunkSize
532-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
533-- at index @i@ and reading up to @count@ elements in the reverse direction
534-- ending at the index @i - count + 1@.
535--
536-- @since 0.7.0
537{-# INLINE readSliceRev #-}
538readSliceRev :: (IsStream t, MonadIO m, Storable a)
539 => Handle -> Int -> Int -> t m a
540readSliceRev h i count = undefined
542-- | Write the given element at the given index in the file.
543--
544-- @since 0.7.0
545{-# INLINE writeIndex #-}
546writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
547writeIndex h i a = undefined
549-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
550-- starting at index @i@ and writing up to @count@ elements in the forward
551-- direction ending at the index @i + count - 1@.
552--
553-- @since 0.7.0
554{-# INLINE writeSlice #-}
555writeSlice :: (IsStream t, Monad m, Storable a)
556 => Handle -> Int -> Int -> t m a -> m ()
557writeSlice h i len s = undefined
559-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
560-- starting at index @i@ and writing up to @count@ elements in the reverse
561-- direction ending at the index @i - count + 1@.
562--
563-- @since 0.7.0
564{-# INLINE writeSliceRev #-}
565writeSliceRev :: (IsStream t, Monad m, Storable a)
566 => Handle -> Int -> Int -> t m a -> m ()
567writeSliceRev arr i len s = undefined
568-}