4-- Module : Streamly.Internal.FileSystem.Handle
5-- Copyright : (c) 2018 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
12module Streamly.Internal.FileSystem.Handle
14 -- ** Read from Handle
28 , readChunksWithBufferOf
30 , toChunksWithBufferOf
34 -- Byte stream write (Folds)
43 -- Byte stream write (Streams)
45 , putBytesWithBufferOf
50 , writeChunksWithBufferOf
52 -- -- * Array stream Write
53 , putChunksWithBufferOf
56 -- -- * Random Access (Seek)
57 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
58 -- files that have random access or seek capability. This type of devices
59 -- include disks, files, memory devices and exclude terminals, pipes,
62 -- XXX need to decide whether to use readFromStepN style or readFromThenTo
63 -- style. The latter is consistent with list enumeration. The former may be
64 -- more unambiguous and it is easier and clearer to specify 0 elements.
66 -- We can also generate the request pattern using a funciton.
69 -- , readFrom -- read from a given position to the end of file
70 -- , readFromRev -- read from a given position the beginning of file
71 -- , readTo -- read from beginning up to the given position
72 -- , readToRev -- read from end to the given position in file
78 -- , readChunksFromToWithBufferOf
79 -- , readChunksFromThenToWithBufferOf
82 -- , writeFrom -- start writing at the given position
84 -- , writeTo -- write from beginning up to the given position
90 -- , writeChunksFromTo
91 -- , writeChunksFromToWithBufferOf
92 -- , writeChunksFromThenToWithBufferOf
96import Control.Monad.IO.Class (MonadIO(..))
97import Data.Word (Word8)
98import Foreign.ForeignPtr (withForeignPtr)
99import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
100import Foreign.Ptr (minusPtr, plusPtr)
101import Foreign.Storable (Storable(..))
102import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
103import System.IO (Handle, hGetBufSome, hPutBuf)
104import Prelude hiding (read)
106import Streamly.Data.Fold (Fold)
107import Streamly.Internal.Data.Fold.Type (Fold2(..))
108import Streamly.Internal.Data.Unfold.Type (Unfold(..))
109import Streamly.Internal.Data.Array.Foreign.Type
110 (Array(..), writeNUnsafe, defaultChunkSize , unsafeFreezeWithShrink)
111import Streamly.Internal.Data.Array.Foreign.Mut.Type (mutableArray)
112import Streamly.Internal.Data.Stream.Serial (SerialT)
113import Streamly.Internal.Data.Stream.StreamK.Type (IsStream, mkStream)
114import Streamly.Internal.Data.Array.Stream.Foreign (lpackArraysChunksOf)
115-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
117import qualified Streamly.Data.Fold as FL
118import qualified Streamly.Internal.Data.Fold.Type as FL
119import qualified Streamly.Internal.Data.Unfold as UF
120import qualified Streamly.Internal.Data.Array.Stream.Foreign as AS
121import qualified Streamly.Internal.Data.Stream.IsStream as S
122import qualified Streamly.Data.Array.Foreign as A
123import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
125-------------------------------------------------------------------------------
127-------------------------------------------------------------------------------
129-- The following references may be useful to build an understanding about the
132-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
133-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
134-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
135-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
136-- https://www.w3.org/TR/FileAPI/ for http file API.
138-------------------------------------------------------------------------------
140-------------------------------------------------------------------------------
142-- | Read a 'ByteArray' from a file handle. If no data is available on the
143-- handle it blocks until some data becomes available. If data is available
144-- then it immediately returns that data without blocking. It reads a maximum
145-- of up to the size requested.
146{-# INLINABLE readArrayUpto #-}
147readArrayUpto :: Int -> Handle -> IO (Array Word8)
148readArrayUpto size h = do
149 ptr <- mallocPlainForeignPtrBytes size
150 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
151 withForeignPtr ptr $ \p -> do
152 n <- hGetBufSome h p size
153 -- XXX shrink only if the diff is significant
155 unsafeFreezeWithShrink $
156 mutableArray ptr (p `plusPtr` n) (p `plusPtr` size)
158-------------------------------------------------------------------------------
159-- Stream of Arrays IO
160-------------------------------------------------------------------------------
162-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
163-- The maximum size of a single array is specified by @size@. The actual size
164-- read may be less than or equal to @size@.
165{-# INLINABLE _toChunksWithBufferOf #-}
166_toChunksWithBufferOf :: (IsStream t, MonadIO m)
167 => Int -> Handle -> t m (Array Word8)
168_toChunksWithBufferOf size h = go
170 -- XXX use cons/nil instead
171 go = mkStream $ \_ yld _ stp -> do
172 arr <- liftIO $ readArrayUpto size h
177-- | @toChunksWithBufferOf size handle@ reads a stream of arrays from the file
178-- handle @handle@. The maximum size of a single array is limited to @size@.
179-- The actual size read may be less than or equal to @size@.
182{-# INLINE_NORMAL toChunksWithBufferOf #-}
183toChunksWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
184toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
186 {-# INLINE_LATE step #-}
188 arr <- liftIO $ readArrayUpto size h
194-- | Unfold the tuple @(bufsize, handle)@ into a stream of 'Word8' arrays.
195-- Read requests to the IO device are performed using a buffer of size
196-- @bufsize@. The size of an array in the resulting stream is always less than
197-- or equal to @bufsize@.
200{-# INLINE_NORMAL readChunksWithBufferOf #-}
201readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Handle) (Array Word8)
202readChunksWithBufferOf = Unfold step return
204 {-# INLINE_LATE step #-}
206 arr <- liftIO $ readArrayUpto size h
210 _ -> D.Yield arr (size, h)
212-- XXX read 'Array a' instead of Word8
214-- | @toChunks handle@ reads a stream of arrays from the specified file
215-- handle. The maximum size of a single array is limited to
216-- @defaultChunkSize@. The actual size read may be less than or equal to
217-- @defaultChunkSize@.
219-- > toChunks = toChunksWithBufferOf defaultChunkSize
222{-# INLINE toChunks #-}
223toChunks :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
224toChunks = toChunksWithBufferOf defaultChunkSize
226-- | Unfolds a handle into a stream of 'Word8' arrays. Requests to the IO
227-- device are performed using a buffer of size
228-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'. The
229-- size of arrays in the resulting stream are therefore less than or equal to
230-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
233{-# INLINE readChunks #-}
234readChunks :: MonadIO m => Unfold m Handle (Array Word8)
235readChunks = UF.supplyFirst defaultChunkSize readChunksWithBufferOf
237-------------------------------------------------------------------------------
238-- Read File to Stream
239-------------------------------------------------------------------------------
241-- TODO for concurrent streams implement readahead IO. We can send multiple
242-- read requests at the same time. For serial case we can use async IO. We can
243-- also control the read throughput in mbps or IOPS.
245-- | Unfolds the tuple @(bufsize, handle)@ into a byte stream, read requests
246-- to the IO device are performed using buffers of @bufsize@.
249{-# INLINE readWithBufferOf #-}
250readWithBufferOf :: MonadIO m => Unfold m (Int, Handle) Word8
251readWithBufferOf = UF.many readChunksWithBufferOf A.read
253-- | @toBytesWithBufferOf bufsize handle@ reads a byte stream from a file
254-- handle, reads are performed in chunks of up to @bufsize@.
257{-# INLINE toBytesWithBufferOf #-}
258toBytesWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
259toBytesWithBufferOf chunkSize h = AS.concat $ toChunksWithBufferOf chunkSize h
262-- Generate a stream of elements of the given type from a file 'Handle'.
263-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
265-- | Unfolds a file handle into a byte stream. IO requests to the device are
266-- performed in sizes of
267-- 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize'.
271read :: MonadIO m => Unfold m Handle Word8
272read = UF.supplyFirst defaultChunkSize readWithBufferOf
274-- | Generate a byte stream from a file 'Handle'.
277{-# INLINE toBytes #-}
278toBytes :: (IsStream t, MonadIO m) => Handle -> t m Word8
279toBytes = AS.concat . toChunks
281-------------------------------------------------------------------------------
283-------------------------------------------------------------------------------
285-------------------------------------------------------------------------------
287-------------------------------------------------------------------------------
289-- | Write an 'Array' to a file handle.
292{-# INLINABLE writeArray #-}
293writeArray :: Storable a => Handle -> Array a -> IO ()
294writeArray _ arr | A.length arr == 0 = return ()
295writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
298 let p = unsafeForeignPtrToPtr aStart
301-------------------------------------------------------------------------------
302-- Stream of Arrays IO
303-------------------------------------------------------------------------------
305-------------------------------------------------------------------------------
307-------------------------------------------------------------------------------
309-- XXX use an unfold to fromObjects or fromUnfold so that we can put any object
310-- | Write a stream of arrays to a handle.
313{-# INLINE putChunks #-}
314putChunks :: (MonadIO m, Storable a)
315 => Handle -> SerialT m (Array a) -> m ()
316putChunks h = S.mapM_ (liftIO . writeArray h)
318-- | @putChunksWithBufferOf bufsize handle stream@ writes a stream of arrays
319-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
320-- The chunk size is only a maximum and the actual writes could be smaller as
321-- we do not split the arrays to fit exactly to the specified size.
324{-# INLINE putChunksWithBufferOf #-}
325putChunksWithBufferOf :: (MonadIO m, Storable a)
326 => Int -> Handle -> SerialT m (Array a) -> m ()
327putChunksWithBufferOf n h xs = putChunks h $ AS.compact n xs
329-- | @putBytesWithBufferOf bufsize handle stream@ writes @stream@ to @handle@
330-- in chunks of @bufsize@. A write is performed to the IO device as soon as we
331-- collect the required input size.
334{-# INLINE putBytesWithBufferOf #-}
335putBytesWithBufferOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
336putBytesWithBufferOf n h m = putChunks h $ S.arraysOf n m
337-- putBytesWithBufferOf n h m = putChunks h $ AS.arraysOf n m
339-- > write = 'writeWithBufferOf' A.defaultChunkSize
341-- | Write a byte stream to a file handle. Accumulates the input in chunks of
342-- up to 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize' before writing.
344-- NOTE: This may perform better than the 'write' fold, you can try this if you
345-- need some extra perf boost.
348{-# INLINE putBytes #-}
349putBytes :: MonadIO m => Handle -> SerialT m Word8 -> m ()
350putBytes = putBytesWithBufferOf defaultChunkSize
352-- | Write a stream of arrays to a handle. Each array in the stream is written
353-- to the device as a separate IO request.
356{-# INLINE writeChunks #-}
357writeChunks :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
358writeChunks h = FL.drainBy (liftIO . writeArray h)
360{-# INLINE writeChunks2 #-}
361writeChunks2 :: (MonadIO m, Storable a) => Fold2 m Handle (Array a) ()
362writeChunks2 = Fold2 (\h arr -> liftIO $ writeArray h arr >> return h) return (\_ -> return ())
364-- | @writeChunksWithBufferOf bufsize handle@ writes a stream of arrays
365-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
366-- We never split an array, if a single array is bigger than the specified size
367-- it emitted as it is. Multiple arrays are coalesed as long as the total size
368-- remains below the specified size.
371{-# INLINE writeChunksWithBufferOf #-}
372writeChunksWithBufferOf :: (MonadIO m, Storable a)
373 => Int -> Handle -> Fold m (Array a) ()
374writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
376-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
379-- Note that if you use a chunk size less than 8K (GHC's default buffer
380-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
381-- do not want buffering to occur at GHC level as well. Same thing applies to
384-- | @writeWithBufferOf reqSize handle@ writes the input stream to @handle@.
385-- Bytes in the input stream are collected into a buffer until we have a chunk
386-- of @reqSize@ and then written to the IO device.
389{-# INLINE writeWithBufferOf #-}
390writeWithBufferOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
391writeWithBufferOf n h = FL.chunksOf n (writeNUnsafe n) (writeChunks h)
393{-# INLINE writeWithBufferOf2 #-}
394writeWithBufferOf2 :: MonadIO m => Int -> Fold2 m Handle Word8 ()
395writeWithBufferOf2 n = FL.chunksOf2 n (writeNUnsafe n) writeChunks2
397-- > write = 'writeWithBufferOf' A.defaultChunkSize
399-- | Write a byte stream to a file handle. Accumulates the input in chunks of
400-- up to 'Streamly.Internal.Data.Array.Foreign.Type.defaultChunkSize' before writing
405write :: MonadIO m => Handle -> Fold m Word8 ()
406write = writeWithBufferOf defaultChunkSize
409write2 :: MonadIO m => Fold2 m Handle Word8 ()
410write2 = writeWithBufferOf2 defaultChunkSize
414write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
415write = toHandleWith A.defaultChunkSize
418-- XXX mmap a file into an array. This could be useful for in-place operations
419-- on a file. For example, we can quicksort the contents of a file by mmapping
422-------------------------------------------------------------------------------
423-- IO with encoding/decoding Unicode characters
424-------------------------------------------------------------------------------
428-- > readUtf8 = decodeUtf8 . read
430-- Read a UTF8 encoded stream of unicode characters from a file handle.
433{-# INLINE readUtf8 #-}
434readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
435readUtf8 = decodeUtf8 . read
438-- > writeUtf8 h s = write h $ encodeUtf8 s
440-- Encode a stream of unicode characters to UTF8 and write it to the given file
441-- handle. Default block buffering applies to the writes.
444{-# INLINE writeUtf8 #-}
445writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
446writeUtf8 h s = write h $ encodeUtf8 s
448-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
449-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
450-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
451-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
455{-# INLINE writeUtf8ByLines #-}
456writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
457writeUtf8ByLines = undefined
459-- | Read UTF-8 lines from a file handle and apply the specified fold to each
460-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
463{-# INLINE readLines #-}
464readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
465readLines h f = foldLines (readUtf8 h) f
467-------------------------------------------------------------------------------
468-- Framing on a sequence
469-------------------------------------------------------------------------------
471-- | Read a stream from a file handle and split it into frames delimited by
472-- the specified sequence of elements. The supplied fold is applied on each
476{-# INLINE readFrames #-}
477readFrames :: (IsStream t, MonadIO m, Storable a)
478 => Array a -> Handle -> Fold m a b -> t m b
479readFrames = undefined -- foldFrames . read
481-- | Write a stream to the given file handle buffering up to frames separated
482-- by the given sequence or up to a maximum of @defaultChunkSize@.
485{-# INLINE writeByFrames #-}
486writeByFrames :: (IsStream t, MonadIO m, Storable a)
487 => Array a -> Handle -> t m a -> m ()
488writeByFrames = undefined
490-------------------------------------------------------------------------------
492-------------------------------------------------------------------------------
494-- | Write collecting the input in sessions of n seconds or if chunkSize
496{-# INLINE writeByChunksOrSessionsOf #-}
497writeByChunksOrSessionsOf :: MonadIO m
498 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
499writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
501-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
503{-# INLINE writeBySessionsOf #-}
504writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
505writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
507-------------------------------------------------------------------------------
508-- Random Access IO (Seek)
509-------------------------------------------------------------------------------
511-- XXX handles could be shared, so we may not want to use the handle state at
512-- all for these APIs. we can use pread and pwrite instead. On windows we will
513-- need to use readFile/writeFile with an offset argument.
515-------------------------------------------------------------------------------
517-- | Read the element at the given index treating the file as an array.
520{-# INLINE readIndex #-}
521readIndex :: Storable a => Handle -> Int -> Maybe a
522readIndex arr i = undefined
524-- NOTE: To represent a range to read we have chosen (start, size) instead of
525-- (start, end). This helps in removing the ambiguity of whether "end" is
526-- included in the range or not.
528-- We could avoid specifying the range to be read and instead use "take size"
529-- on the stream, but it may end up reading more and then consume it partially.
531-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
532-- from @handle@ starting at the offset @pos@ from the beginning of the file.
534-- Reads are performed in chunks of size @chunkSize@. For block devices, to
535-- avoid reading partial blocks @chunkSize@ must align with the block size of
536-- the underlying device. If the underlying block size is unknown, it is a good
537-- idea to keep it a multiple 4KiB. This API ensures that the start of each
538-- chunk is aligned with @chunkSize@ from second chunk onwards.
540{-# INLINE readSliceWith #-}
541readSliceWith :: (IsStream t, MonadIO m, Storable a)
542 => Int -> Handle -> Int -> Int -> t m a
543readSliceWith chunkSize h pos len = undefined
545-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
546-- at index @i@ and reading up to @count@ elements in the forward direction
547-- ending at the index @i + count - 1@.
550{-# INLINE readSlice #-}
551readSlice :: (IsStream t, MonadIO m, Storable a)
552 => Handle -> Int -> Int -> t m a
553readSlice = readSliceWith A.defaultChunkSize
555-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
556-- at index @i@ and reading up to @count@ elements in the reverse direction
557-- ending at the index @i - count + 1@.
560{-# INLINE readSliceRev #-}
561readSliceRev :: (IsStream t, MonadIO m, Storable a)
562 => Handle -> Int -> Int -> t m a
563readSliceRev h i count = undefined
565-- | Write the given element at the given index in the file.
568{-# INLINE writeIndex #-}
569writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
570writeIndex h i a = undefined
572-- | @writeSlice 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 forward
574-- direction ending at the index @i + count - 1@.
577{-# INLINE writeSlice #-}
578writeSlice :: (IsStream t, Monad m, Storable a)
579 => Handle -> Int -> Int -> t m a -> m ()
580writeSlice h i len s = undefined
582-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
583-- starting at index @i@ and writing up to @count@ elements in the reverse
584-- direction ending at the index @i - count + 1@.
587{-# INLINE writeSliceRev #-}
588writeSliceRev :: (IsStream t, Monad m, Storable a)
589 => Handle -> Int -> Int -> t m a -> m ()
590writeSliceRev arr i len s = undefined
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list