on f2eb96a help sign in
581 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)
123import Streamly.Internal.Data.Unboxed (Unboxed)
124-- import System.IO (Handle, hGetBufSome, hPutBuf)
125import System.IO (IOMode)
126import Prelude hiding (read)
128import qualified GHC.IO.FD as FD
129import qualified GHC.IO.Device as RawIO
131import Streamly.Internal.Data.Array.Unboxed.Type
132 (Array(..), byteLength, unsafeFreeze, asPtrUnsafe)
133import Streamly.Internal.System.IO (defaultChunkSize)
134import Streamly.Internal.Data.Stream.Type (Stream)
135import Streamly.Internal.Data.Stream.IsStream.Type
136 (IsStream, mkStream, fromStreamD)
137#if !defined(mingw32_HOST_OS)
138{-
139import Streamly.Internal.Data.Stream.IsStream.Type (toStreamD)
140import Streamly.Internal.System.IOVec (groupIOVecsOf)
141import qualified Streamly.Internal.FileSystem.FDIO as RawIO hiding (write)
142import qualified Streamly.Internal.System.IOVec.Type as RawIO
143-}
144#endif
145-- import Streamly.Data.Fold (Fold)
146-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
148import qualified Streamly.Data.Array.Unboxed as A
149import qualified Streamly.Internal.Data.Array.Unboxed.Mut.Type as MArray
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 arr <- MArray.newPinnedArrayBytes size
218 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
219 MArray.asPtrUnsafe arr $ \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 $ arr { MArray.arrEnd = n, MArray.arrBound = 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 :: Unboxed 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 {arrEnd = arrBound 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{-
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 asPtrUnsafe iov $ \p ->
270 RawIO.writevAll fd p (A.length iov)
271-}
272#endif
274-------------------------------------------------------------------------------
275-- Stream of Arrays IO
276-------------------------------------------------------------------------------
278-- | @readArraysOfUpto size h@ reads a stream of arrays from file handle @h@.
279-- The maximum size of a single array is specified by @size@. The actual size
280-- read may be less than or equal to @size@.
281{-# INLINE _readArraysOfUpto #-}
282_readArraysOfUpto :: (IsStream t, MonadIO m)
283 => Int -> Handle -> t m (Array Word8)
284_readArraysOfUpto size h = go
285 where
286 -- XXX use cons/nil instead
287 go = mkStream $ \_ yld _ stp -> do
288 arr <- liftIO $ readArrayUpto size h
289 if A.length arr == 0
290 then stp
291 else yld arr go
293{-# INLINE_NORMAL readArraysOfUpto #-}
294readArraysOfUpto :: (IsStream t, MonadIO m)
295 => Int -> Handle -> t m (Array Word8)
296readArraysOfUpto size h = fromStreamD (D.Stream step ())
297 where
298 {-# INLINE_LATE step #-}
299 step _ _ = do
300 arr <- liftIO $ readArrayUpto size h
301 return $
302 case A.length arr of
303 0 -> D.Stop
304 _ -> D.Yield arr ()
306-- XXX read 'Array a' instead of Word8
307--
308-- | @readArrays h@ reads a stream of arrays from file handle @h@.
309-- The maximum size of a single array is limited to @defaultChunkSize@.
310-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
311-- on the 'Handle'.
312--
313-- > readArrays = readArraysOfUpto defaultChunkSize
314--
315-- @since 0.7.0
316{-# INLINE readArrays #-}
317readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
318readArrays = readArraysOfUpto defaultChunkSize
320-------------------------------------------------------------------------------
321-- Read File to Stream
322-------------------------------------------------------------------------------
324-- TODO for concurrent streams implement readahead IO. We can send multiple
325-- read requests at the same time. For serial case we can use async IO. We can
326-- also control the read throughput in mbps or IOPS.
328-- | @readInChunksOf chunkSize handle@ reads a byte stream from a file handle,
329-- reads are performed in chunks of up to @chunkSize@. The stream ends as soon
330-- as EOF is encountered.
331--
332{-# INLINE readInChunksOf #-}
333readInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
334readInChunksOf chunkSize h = AS.concat $ readArraysOfUpto chunkSize h
336-- TODO
337-- read :: (IsStream t, MonadIO m, Unboxed a) => Handle -> t m a
338--
339-- > read = 'readByChunks' A.defaultChunkSize
340-- | Generate a stream of elements of the given type from a file 'Handle'. The
341-- stream ends when EOF is encountered.
342--
343-- @since 0.7.0
344{-# INLINE read #-}
345read :: (IsStream t, MonadIO m) => Handle -> t m Word8
346read = AS.concat . readArrays
348-------------------------------------------------------------------------------
349-- Writing
350-------------------------------------------------------------------------------
352-- | Write a stream of arrays to a handle.
353--
354-- @since 0.7.0
355{-# INLINE writeArrays #-}
356writeArrays :: (MonadIO m, Unboxed a) => Handle -> Stream m (Array a) -> m ()
357writeArrays h = S.mapM_ (liftIO . writeArray h)
359-- | Write a stream of arrays to a handle after coalescing them in chunks of
360-- specified size. The chunk size is only a maximum and the actual writes could
361-- be smaller than that as we do not split the arrays to fit them to the
362-- specified size.
363--
364-- @since 0.7.0
365{-# INLINE writeArraysPackedUpto #-}
366writeArraysPackedUpto :: (MonadIO m, Unboxed a)
367 => Int -> Handle -> Stream m (Array a) -> m ()
368writeArraysPackedUpto n h xs = writeArrays h $ AS.compact n xs
370#if !defined(mingw32_HOST_OS)
371{-
372-- XXX this is incomplete
373-- | Write a stream of 'IOVec' arrays to a handle.
374--
375-- @since 0.7.0
376{-# INLINE writev #-}
377writev :: MonadIO m => Handle -> Stream m (Array RawIO.IOVec) -> m ()
378writev h = S.mapM_ (liftIO . writeIOVec h)
380-- XXX this is incomplete
381-- | Write a stream of arrays to a handle after grouping them in 'IOVec' arrays
382-- of up to a maximum total size. Writes are performed using gather IO via
383-- @writev@ system call. The maximum number of entries in each 'IOVec' group
384-- limited to 512.
385--
386-- @since 0.7.0
387{-# INLINE _writevArraysPackedUpto #-}
388_writevArraysPackedUpto :: MonadIO m
389 => Int -> Handle -> Stream m (Array a) -> m ()
390_writevArraysPackedUpto n h xs =
391 writev h $ fromStreamD $ groupIOVecsOf n 512 (toStreamD xs)
392-}
393#endif
395-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
396--
397-- XXX test this
398-- Note that if you use a chunk size less than 8K (GHC's default buffer
399-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
400-- do not want buffering to occur at GHC level as well. Same thing applies to
401-- writes as well.
403-- | Like 'write' but provides control over the write buffer. Output will
404-- be written to the IO device as soon as we collect the specified number of
405-- input elements.
406--
407-- @since 0.7.0
408{-# INLINE writeInChunksOf #-}
409writeInChunksOf :: MonadIO m => Int -> Handle -> Stream m Word8 -> m ()
410writeInChunksOf n h m = writeArrays h $ AS.arraysOf n m
412-- > write = 'writeInChunksOf' A.defaultChunkSize
413--
414-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
415-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
416-- depends on the 'IOMode' and the current seek position of the handle.
417--
418-- @since 0.7.0
419{-# INLINE write #-}
420write :: MonadIO m => Handle -> Stream m Word8 -> m ()
421write = writeInChunksOf defaultChunkSize
423{-
424{-# INLINE write #-}
425write :: (MonadIO m, Unboxed a) => Handle -> Stream m a -> m ()
426write = toHandleWith A.defaultChunkSize
427-}
429-------------------------------------------------------------------------------
430-- IO with encoding/decoding Unicode characters
431-------------------------------------------------------------------------------
433{-
434-- |
435-- > readUtf8 = decodeUtf8 . read
436--
437-- Read a UTF8 encoded stream of unicode characters from a file handle.
438--
439-- @since 0.7.0
440{-# INLINE readUtf8 #-}
441readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
442readUtf8 = decodeUtf8 . read
444-- |
445-- > writeUtf8 h s = write h $ encodeUtf8 s
446--
447-- Encode a stream of unicode characters to UTF8 and write it to the given file
448-- handle. Default block buffering applies to the writes.
449--
450-- @since 0.7.0
451{-# INLINE writeUtf8 #-}
452writeUtf8 :: MonadIO m => Handle -> Stream m Char -> m ()
453writeUtf8 h s = write h $ encodeUtf8 s
455-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
456-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
457-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
458-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
459-- option.
460--
461-- @since 0.7.0
462{-# INLINE writeUtf8ByLines #-}
463writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
464writeUtf8ByLines = undefined
466-- | Read UTF-8 lines from a file handle and apply the specified fold to each
467-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
468--
469-- @since 0.7.0
470{-# INLINE readLines #-}
471readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
472readLines h f = foldLines (readUtf8 h) f
474-------------------------------------------------------------------------------
475-- Framing on a sequence
476-------------------------------------------------------------------------------
478-- | Read a stream from a file handle and split it into frames delimited by
479-- the specified sequence of elements. The supplied fold is applied on each
480-- frame.
481--
482-- @since 0.7.0
483{-# INLINE readFrames #-}
484readFrames :: (IsStream t, MonadIO m, Unboxed a)
485 => Array a -> Handle -> Fold m a b -> t m b
486readFrames = undefined -- foldFrames . read
488-- | Write a stream to the given file handle buffering up to frames separated
489-- by the given sequence or up to a maximum of @defaultChunkSize@.
490--
491-- @since 0.7.0
492{-# INLINE writeByFrames #-}
493writeByFrames :: (IsStream t, MonadIO m, Unboxed a)
494 => Array a -> Handle -> t m a -> m ()
495writeByFrames = undefined
497-------------------------------------------------------------------------------
498-- Random Access IO (Seek)
499-------------------------------------------------------------------------------
501-- XXX handles could be shared, so we may not want to use the handle state at
502-- all for these APIs. we can use pread and pwrite instead. On windows we will
503-- need to use readFile/writeFile with an offset argument.
505-------------------------------------------------------------------------------
507-- | Read the element at the given index treating the file as an array.
508--
509-- @since 0.7.0
510{-# INLINE readIndex #-}
511readIndex :: Unboxed a => Handle -> Int -> Maybe a
512readIndex arr i = undefined
514-- NOTE: To represent a range to read we have chosen (start, size) instead of
515-- (start, end). This helps in removing the ambiguity of whether "end" is
516-- included in the range or not.
517--
518-- We could avoid specifying the range to be read and instead use "take size"
519-- on the stream, but it may end up reading more and then consume it partially.
521-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
522-- from @handle@ starting at the offset @pos@ from the beginning of the file.
523--
524-- Reads are performed in chunks of size @chunkSize@. For block devices, to
525-- avoid reading partial blocks @chunkSize@ must align with the block size of
526-- the underlying device. If the underlying block size is unknown, it is a good
527-- idea to keep it a multiple 4KiB. This API ensures that the start of each
528-- chunk is aligned with @chunkSize@ from second chunk onwards.
529--
530{-# INLINE readSliceWith #-}
531readSliceWith :: (IsStream t, MonadIO m, Unboxed a)
532 => Int -> Handle -> Int -> Int -> t m a
533readSliceWith chunkSize h pos len = undefined
535-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
536-- at index @i@ and reading up to @count@ elements in the forward direction
537-- ending at the index @i + count - 1@.
538--
539-- @since 0.7.0
540{-# INLINE readSlice #-}
541readSlice :: (IsStream t, MonadIO m, Unboxed a)
542 => Handle -> Int -> Int -> t m a
543readSlice = readSliceWith defaultChunkSize
545-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
546-- at index @i@ and reading up to @count@ elements in the reverse direction
547-- ending at the index @i - count + 1@.
548--
549-- @since 0.7.0
550{-# INLINE readSliceRev #-}
551readSliceRev :: (IsStream t, MonadIO m, Unboxed a)
552 => Handle -> Int -> Int -> t m a
553readSliceRev h i count = undefined
555-- | Write the given element at the given index in the file.
556--
557-- @since 0.7.0
558{-# INLINE writeIndex #-}
559writeIndex :: (MonadIO m, Unboxed a) => Handle -> Int -> a -> m ()
560writeIndex h i a = undefined
562-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
563-- starting at index @i@ and writing up to @count@ elements in the forward
564-- direction ending at the index @i + count - 1@.
565--
566-- @since 0.7.0
567{-# INLINE writeSlice #-}
568writeSlice :: (IsStream t, Monad m, Unboxed a)
569 => Handle -> Int -> Int -> t m a -> m ()
570writeSlice h i len s = undefined
572-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
573-- starting at index @i@ and writing up to @count@ elements in the reverse
574-- direction ending at the index @i - count + 1@.
575--
576-- @since 0.7.0
577{-# INLINE writeSliceRev #-}
578writeSliceRev :: (IsStream t, Monad m, Unboxed a)
579 => Handle -> Int -> Int -> t m a -> m ()
580writeSliceRev arr i len s = undefined
581-}