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