on fc86706 help sign in
577 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)
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, asPtrUnsafe)
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
145#endif
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-------------------------------------------------------------------------------
155-- References
156-------------------------------------------------------------------------------
157--
158-- The following references may be useful to build an understanding about the
159-- file API design:
160--
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-------------------------------------------------------------------------------
168-- Handles
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.
174--
175newtype Handle = Handle FD.FD
177-- | File handle for standard input
178stdin :: Handle
179stdin = Handle FD.stdin
181-- | File handle for standard output
182stdout :: Handle
183stdout = Handle FD.stdout
185-- | File handle for standard error
186stderr :: Handle
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
191-- instead?
192--
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.
202--
203openFile :: FilePath -> IOMode -> IO Handle
204openFile path mode = Handle . fst <$> FD.openFile path mode True
206-------------------------------------------------------------------------------
207-- Array IO (Input)
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
223#else
224 n <- RawIO.read fd p size
225#endif
226 -- XXX shrink only if the diff is significant
227 -- Use unsafeFreezeWithShrink
228 return
229 $ unsafeFreeze
230 $ fromForeignPtrUnsafe ptr (p `plusPtr` n) (p `plusPtr` size)
232-------------------------------------------------------------------------------
233-- Array IO (output)
234-------------------------------------------------------------------------------
236-- | Write an 'Array' to a file handle.
237--
238-- @since 0.7.0
239{-# INLINABLE writeArray #-}
240writeArray :: Storable a => Handle -> Array a -> IO ()
241writeArray _ arr | A.length arr == 0 = return ()
242writeArray (Handle fd) arr =
243 asPtrUnsafe arr $ \p ->
244 -- RawIO.writeAll fd (castPtr p) aLen
245#if MIN_VERSION_base(4,15,0)
246 RawIO.write fd (castPtr p) 0 aLen
247#else
248 RawIO.write fd (castPtr p) aLen
249#endif
250 {-
251 -- Experiment to compare "writev" based IO with "write" based IO.
252 iov <- A.newArray 1
253 let iov' = iov {aEnd = aBound iov}
254 A.writeIndex iov' 0 (RawIO.IOVec (castPtr p) (fromIntegral aLen))
255 RawIO.writevAll fd (unsafeForeignPtrToPtr (aStart iov')) 1
256 -}
257 where
258 aLen = byteLength arr
260#if !defined(mingw32_HOST_OS)
261-- | Write an array of 'IOVec' to a file handle.
262--
263-- @since 0.7.0
264{-# INLINABLE writeIOVec #-}
265writeIOVec :: Handle -> Array RawIO.IOVec -> IO ()
266writeIOVec _ iov | A.length iov == 0 = return ()
267writeIOVec (Handle fd) iov =
268 asPtrUnsafe iov $ \p ->
269 RawIO.writevAll fd p (A.length iov)
270#endif
272-------------------------------------------------------------------------------
273-- Stream of Arrays IO
274-------------------------------------------------------------------------------
276-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
277-- The maximum size of a single array is specified by @size@. The actual size
278-- read may be less than or equal to @size@.
279{-# INLINE _readArraysOfUpto #-}
280_readArraysOfUpto :: (IsStream t, MonadIO m)
281 => Int -> Handle -> t m (Array Word8)
282_readArraysOfUpto size h = go
283 where
284 -- XXX use cons/nil instead
285 go = mkStream $ \_ yld _ stp -> do
286 arr <- liftIO $ readArrayUpto size h
287 if A.length arr == 0
288 then stp
289 else yld arr go
291{-# INLINE_NORMAL readArraysOfUpto #-}
292readArraysOfUpto :: (IsStream t, MonadIO m)
293 => Int -> Handle -> t m (Array Word8)
294readArraysOfUpto size h = fromStreamD (D.Stream step ())
295 where
296 {-# INLINE_LATE step #-}
297 step _ _ = do
298 arr <- liftIO $ readArrayUpto size h
299 return $
300 case A.length arr of
301 0 -> D.Stop
302 _ -> D.Yield arr ()
304-- XXX read 'Array a' instead of Word8
305--
306-- | @readArrays h@ reads a stream of arrays from file handle @h@.
307-- The maximum size of a single array is limited to @defaultChunkSize@.
308-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
309-- on the 'Handle'.
310--
311-- > readArrays = readArraysOfUpto defaultChunkSize
312--
313-- @since 0.7.0
314{-# INLINE readArrays #-}
315readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
316readArrays = readArraysOfUpto defaultChunkSize
318-------------------------------------------------------------------------------
319-- Read File to Stream
320-------------------------------------------------------------------------------
322-- TODO for concurrent streams implement readahead IO. We can send multiple
323-- read requests at the same time. For serial case we can use async IO. We can
324-- also control the read throughput in mbps or IOPS.
326-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
327-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
328-- as EOF is encountered.
329--
330{-# INLINE readInChunksOf #-}
331readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
332readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
334-- TODO
335-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
336--
337-- > read = 'readByChunks' A.defaultChunkSize
338-- | Generate a stream of elements of the given type from a file 'Handle'. The
339-- stream ends when EOF is encountered.
340--
341-- @since 0.7.0
342{-# INLINE read #-}
343read :: (IsStream t, MonadIO m) => Handle -> t m Word8
344read = AS.concat . readArrays
346-------------------------------------------------------------------------------
347-- Writing
348-------------------------------------------------------------------------------
350-- | Write a stream of arrays to a handle.
351--
352-- @since 0.7.0
353{-# INLINE writeArrays #-}
354writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
355writeArrays h = S.mapM_ (liftIO . writeArray h)
357-- | Write a stream of arrays to a handle after coalescing them in chunks of
358-- specified size. The chunk size is only a maximum and the actual writes could
359-- be smaller than that as we do not split the arrays to fit them to the
360-- specified size.
361--
362-- @since 0.7.0
363{-# INLINE writeArraysPackedUpto #-}
364writeArraysPackedUpto :: (MonadIO m, Storable a)
365 => Int -> Handle -> SerialT m (Array a) -> m ()
366writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
368#if !defined(mingw32_HOST_OS)
369-- XXX this is incomplete
370-- | Write a stream of 'IOVec' arrays to a handle.
371--
372-- @since 0.7.0
373{-# INLINE writev #-}
374writev :: MonadIO m => Handle -> SerialT m (Array RawIO.IOVec) -> m ()
375writev h = S.mapM_ (liftIO . writeIOVec h)
377-- XXX this is incomplete
378-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
379-- of up to a maximum total size. Writes are performed using gather IO via
380-- @writev@ system call. The maximum number of entries in each 'IOVec' group
381-- limited to 512.
382--
383-- @since 0.7.0
384{-# INLINE _writevArraysPackedUpto #-}
385_writevArraysPackedUpto :: MonadIO m
386 => Int -> Handle -> SerialT m (Array a) -> m ()
387_writevArraysPackedUpto n h xs =
388 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
389#endif
391-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
392--
393-- XXX test this
394-- Note that if you use a chunk size less than 8K (GHC's default buffer
395-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
396-- do not want buffering to occur at GHC level as well. Same thing applies to
397-- writes as well.
399-- | Like 'write' but provides control over the write buffer. Output will
400-- be written to the IO device as soon as we collect the specified number of
401-- input elements.
402--
403-- @since 0.7.0
404{-# INLINE writeInChunksOf #-}
405writeInChunksOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
406writeInChunksOf n h m = writeArrays h $ AS.arraysOf n m
408-- > write = 'writeInChunksOf' A.defaultChunkSize
409--
410-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
411-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
412-- depends on the 'IOMode' and the current seek position of the handle.
413--
414-- @since 0.7.0
415{-# INLINE write #-}
416write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
417write = writeInChunksOf defaultChunkSize
419{-
420{-# INLINE write #-}
421write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
422write = toHandleWith A.defaultChunkSize
423-}
425-------------------------------------------------------------------------------
426-- IO with encoding/decoding Unicode characters
427-------------------------------------------------------------------------------
429{-
430-- |
431-- > readUtf8 = decodeUtf8 . read
432--
433-- Read a UTF8 encoded stream of unicode characters from a file handle.
434--
435-- @since 0.7.0
436{-# INLINE readUtf8 #-}
437readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
438readUtf8 = decodeUtf8 . read
440-- |
441-- > writeUtf8 h s = write h $ encodeUtf8 s
442--
443-- Encode a stream of unicode characters to UTF8 and write it to the given file
444-- handle. Default block buffering applies to the writes.
445--
446-- @since 0.7.0
447{-# INLINE writeUtf8 #-}
448writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
449writeUtf8 h s = write h $ encodeUtf8 s
451-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
452-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
453-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
454-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
455-- option.
456--
457-- @since 0.7.0
458{-# INLINE writeUtf8ByLines #-}
459writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
460writeUtf8ByLines = undefined
462-- | Read UTF-8 lines from a file handle and apply the specified fold to each
463-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
464--
465-- @since 0.7.0
466{-# INLINE readLines #-}
467readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
468readLines h f = foldLines (readUtf8 h) f
470-------------------------------------------------------------------------------
471-- Framing on a sequence
472-------------------------------------------------------------------------------
474-- | Read a stream from a file handle and split it into frames delimited by
475-- the specified sequence of elements. The supplied fold is applied on each
476-- frame.
477--
478-- @since 0.7.0
479{-# INLINE readFrames #-}
480readFrames :: (IsStream t, MonadIO m, Storable a)
481 => Array a -> Handle -> Fold m a b -> t m b
482readFrames = undefined -- foldFrames . read
484-- | Write a stream to the given file handle buffering up to frames separated
485-- by the given sequence or up to a maximum of @defaultChunkSize@.
486--
487-- @since 0.7.0
488{-# INLINE writeByFrames #-}
489writeByFrames :: (IsStream t, MonadIO m, Storable a)
490 => Array a -> Handle -> t m a -> m ()
491writeByFrames = undefined
493-------------------------------------------------------------------------------
494-- Random Access IO (Seek)
495-------------------------------------------------------------------------------
497-- XXX handles could be shared, so we may not want to use the handle state at
498-- all for these APIs. we can use pread and pwrite instead. On windows we will
499-- need to use readFile/writeFile with an offset argument.
501-------------------------------------------------------------------------------
503-- | Read the element at the given index treating the file as an array.
504--
505-- @since 0.7.0
506{-# INLINE readIndex #-}
507readIndex :: Storable a => Handle -> Int -> Maybe a
508readIndex arr i = undefined
510-- NOTE: To represent a range to read we have chosen (start, size) instead of
511-- (start, end). This helps in removing the ambiguity of whether "end" is
512-- included in the range or not.
513--
514-- We could avoid specifying the range to be read and instead use "take size"
515-- on the stream, but it may end up reading more and then consume it partially.
517-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
518-- from @handle@ starting at the offset @pos@ from the beginning of the file.
519--
520-- Reads are performed in chunks of size @chunkSize@. For block devices, to
521-- avoid reading partial blocks @chunkSize@ must align with the block size of
522-- the underlying device. If the underlying block size is unknown, it is a good
523-- idea to keep it a multiple 4KiB. This API ensures that the start of each
524-- chunk is aligned with @chunkSize@ from second chunk onwards.
525--
526{-# INLINE readSliceWith #-}
527readSliceWith :: (IsStream t, MonadIO m, Storable a)
528 => Int -> Handle -> Int -> Int -> t m a
529readSliceWith chunkSize h pos len = undefined
531-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
532-- at index @i@ and reading up to @count@ elements in the forward direction
533-- ending at the index @i + count - 1@.
534--
535-- @since 0.7.0
536{-# INLINE readSlice #-}
537readSlice :: (IsStream t, MonadIO m, Storable a)
538 => Handle -> Int -> Int -> t m a
539readSlice = readSliceWith defaultChunkSize
541-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
542-- at index @i@ and reading up to @count@ elements in the reverse direction
543-- ending at the index @i - count + 1@.
544--
545-- @since 0.7.0
546{-# INLINE readSliceRev #-}
547readSliceRev :: (IsStream t, MonadIO m, Storable a)
548 => Handle -> Int -> Int -> t m a
549readSliceRev h i count = undefined
551-- | Write the given element at the given index in the file.
552--
553-- @since 0.7.0
554{-# INLINE writeIndex #-}
555writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
556writeIndex h i a = undefined
558-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
559-- starting at index @i@ and writing up to @count@ elements in the forward
560-- direction ending at the index @i + count - 1@.
561--
562-- @since 0.7.0
563{-# INLINE writeSlice #-}
564writeSlice :: (IsStream t, Monad m, Storable a)
565 => Handle -> Int -> Int -> t m a -> m ()
566writeSlice h i len s = undefined
568-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
569-- starting at index @i@ and writing up to @count@ elements in the reverse
570-- direction ending at the index @i - count + 1@.
571--
572-- @since 0.7.0
573{-# INLINE writeSliceRev #-}
574writeSliceRev :: (IsStream t, Monad m, Storable a)
575 => Handle -> Int -> Int -> t m a -> m ()
576writeSliceRev arr i len s = undefined
577-}