2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
11-- Module : Streamly.Internal.FileSystem.Handle
12-- Copyright : (c) 2018 Composewell Technologies
15-- Maintainer : streamly@composewell.com
16-- Stability : experimental
19module Streamly.Internal.FileSystem.Handle
21 -- ** Read from Handle
36 , readChunksWithBufferOf
38 , toChunksWithBufferOf
43 -- Byte stream write (Folds)
52 -- Byte stream write (Streams)
54 , fromBytesWithBufferOf
59 , writeChunksWithBufferOf
61 -- -- * Array stream Write
62 , fromChunksWithBufferOf
69 -- -- * Random Access (Seek)
70 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
71 -- files that have random access or seek capability. This type of devices
72 -- include disks, files, memory devices and exclude terminals, pipes,
75 -- XXX need to decide whether to use readFromStepN style or readFromThenTo
76 -- style. The latter is consistent with list enumeration. The former may be
77 -- more unambiguous and it is easier and clearer to specify 0 elements.
79 -- We can also generate the request pattern using a funciton.
82 -- , readFrom -- read from a given position to the end of file
83 -- , readFromRev -- read from a given position the beginning of file
84 -- , readTo -- read from beginning up to the given position
85 -- , readToRev -- read from end to the given position in file
91 -- , readChunksFromToWithBufferOf
92 -- , readChunksFromThenToWithBufferOf
95 -- , writeFrom -- start writing at the given position
97 -- , writeTo -- write from beginning up to the given position
103 -- , writeChunksFromTo
104 -- , writeChunksFromToWithBufferOf
105 -- , writeChunksFromThenToWithBufferOf
109import Control.Monad.IO.Class (MonadIO(..))
110import Data.Word (Word8)
111import Foreign.ForeignPtr (withForeignPtr)
112import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
113import Foreign.Ptr (minusPtr, plusPtr)
114import Foreign.Storable (Storable(..))
115import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
116import System.IO (Handle, hGetBufSome, hPutBuf, stdin, stdout)
117import Prelude hiding (read)
119import Streamly (MonadAsync)
120import Streamly.Data.Fold (Fold)
121import Streamly.Internal.Data.Fold.Types (Fold2(..))
122import Streamly.Internal.Data.Unfold.Types (Unfold(..))
123import Streamly.Internal.Memory.Array.Types
124 (Array(..), writeNUnsafe, defaultChunkSize, shrinkToFit,
126import Streamly.Internal.Data.Stream.Serial (SerialT)
127import Streamly.Internal.Data.Stream.StreamK.Type (IsStream, mkStream)
128-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
130import qualified Streamly.Data.Fold as FL
131import qualified Streamly.Internal.Data.Fold.Types as FL
132import qualified Streamly.Internal.Data.Unfold as UF
133import qualified Streamly.Internal.Memory.Array as IA
134import qualified Streamly.Internal.Memory.ArrayStream as AS
135import qualified Streamly.Internal.Prelude as S
136import qualified Streamly.Memory.Array as A
137import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
139-------------------------------------------------------------------------------
141-------------------------------------------------------------------------------
143-- The following references may be useful to build an understanding about the
146-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
147-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
148-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
149-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
150-- https://www.w3.org/TR/FileAPI/ for http file API.
152-------------------------------------------------------------------------------
154-------------------------------------------------------------------------------
156-- | Read a 'ByteArray' from a file handle. If no data is available on the
157-- handle it blocks until some data becomes available. If data is available
158-- then it immediately returns that data without blocking. It reads a maximum
159-- of up to the size requested.
160{-# INLINABLE readArrayUpto #-}
161readArrayUpto :: Int -> Handle -> IO (Array Word8)
162readArrayUpto size h = do
163 ptr <- mallocPlainForeignPtrBytes size
164 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
165 withForeignPtr ptr $ \p -> do
166 n <- hGetBufSome h p size
169 , aEnd = p `plusPtr` n
170 , aBound = p `plusPtr` size
172 -- XXX shrink only if the diff is significant
175-------------------------------------------------------------------------------
176-- Stream of Arrays IO
177-------------------------------------------------------------------------------
179-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
180-- The maximum size of a single array is specified by @size@. The actual size
181-- read may be less than or equal to @size@.
182{-# INLINABLE _toChunksWithBufferOf #-}
183_toChunksWithBufferOf :: (IsStream t, MonadIO m)
184 => Int -> Handle -> t m (Array Word8)
185_toChunksWithBufferOf size h = go
187 -- XXX use cons/nil instead
188 go = mkStream $ \_ yld _ stp -> do
189 arr <- liftIO $ readArrayUpto size h
194-- | @toChunksWithBufferOf size handle@ reads a stream of arrays from the file
195-- handle @handle@. The maximum size of a single array is limited to @size@.
196-- The actual size read may be less than or equal to @size@.
199{-# INLINE_NORMAL toChunksWithBufferOf #-}
200toChunksWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
201toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
203 {-# INLINE_LATE step #-}
205 arr <- liftIO $ readArrayUpto size h
211-- | Unfold the tuple @(bufsize, handle)@ into a stream of 'Word8' arrays.
212-- Read requests to the IO device are performed using a buffer of size
213-- @bufsize@. The size of an array in the resulting stream is always less than
214-- or equal to @bufsize@.
217{-# INLINE_NORMAL readChunksWithBufferOf #-}
218readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Handle) (Array Word8)
219readChunksWithBufferOf = Unfold step return
221 {-# INLINE_LATE step #-}
223 arr <- liftIO $ readArrayUpto size h
227 _ -> D.Yield arr (size, h)
229-- XXX read 'Array a' instead of Word8
231-- | @toChunks handle@ reads a stream of arrays from the specified file
232-- handle. The maximum size of a single array is limited to
233-- @defaultChunkSize@. The actual size read may be less than or equal to
234-- @defaultChunkSize@.
236-- > toChunks = toChunksWithBufferOf defaultChunkSize
239{-# INLINE toChunks #-}
240toChunks :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
241toChunks = toChunksWithBufferOf defaultChunkSize
243-- | Read a stream of chunks from standard input. The maximum size of a single
244-- chunk is limited to @defaultChunkSize@. The actual size read may be less
245-- than @defaultChunkSize@.
247-- > getChunks = toChunks stdin
251{-# INLINE getChunks #-}
252getChunks :: (IsStream t, MonadIO m) => t m (Array Word8)
253getChunks = toChunks stdin
255-- | Read a stream of bytes from standard input.
257-- > getBytes = toBytes stdin
261{-# INLINE getBytes #-}
262getBytes :: (IsStream t, MonadIO m) => t m Word8
263getBytes = toBytes stdin
265-- | Unfolds a handle into a stream of 'Word8' arrays. Requests to the IO
266-- device are performed using a buffer of size
267-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. The
268-- size of arrays in the resulting stream are therefore less than or equal to
269-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
272{-# INLINE readChunks #-}
273readChunks :: MonadIO m => Unfold m Handle (Array Word8)
274readChunks = UF.supplyFirst readChunksWithBufferOf defaultChunkSize
276-------------------------------------------------------------------------------
277-- Read File to Stream
278-------------------------------------------------------------------------------
280-- TODO for concurrent streams implement readahead IO. We can send multiple
281-- read requests at the same time. For serial case we can use async IO. We can
282-- also control the read throughput in mbps or IOPS.
284-- | Unfolds the tuple @(bufsize, handle)@ into a byte stream, read requests
285-- to the IO device are performed using buffers of @bufsize@.
288{-# INLINE readWithBufferOf #-}
289readWithBufferOf :: MonadIO m => Unfold m (Int, Handle) Word8
290readWithBufferOf = UF.concat readChunksWithBufferOf A.read
292-- | @toBytesWithBufferOf bufsize handle@ reads a byte stream from a file
293-- handle, reads are performed in chunks of up to @bufsize@.
296{-# INLINE toBytesWithBufferOf #-}
297toBytesWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
298toBytesWithBufferOf chunkSize h = AS.concat $ toChunksWithBufferOf chunkSize h
301-- Generate a stream of elements of the given type from a file 'Handle'.
302-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
304-- | Unfolds a file handle into a byte stream. IO requests to the device are
305-- performed in sizes of
306-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
310read :: MonadIO m => Unfold m Handle Word8
311read = UF.supplyFirst readWithBufferOf defaultChunkSize
313-- | Generate a byte stream from a file 'Handle'.
316{-# INLINE toBytes #-}
317toBytes :: (IsStream t, MonadIO m) => Handle -> t m Word8
318toBytes = AS.concat . toChunks
320-------------------------------------------------------------------------------
322-------------------------------------------------------------------------------
324-------------------------------------------------------------------------------
326-------------------------------------------------------------------------------
328-- | Write an 'Array' to a file handle.
331{-# INLINABLE writeArray #-}
332writeArray :: Storable a => Handle -> Array a -> IO ()
333writeArray _ arr | A.length arr == 0 = return ()
334writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
337 let p = unsafeForeignPtrToPtr aStart
340-------------------------------------------------------------------------------
341-- Stream of Arrays IO
342-------------------------------------------------------------------------------
344-------------------------------------------------------------------------------
346-------------------------------------------------------------------------------
348-- XXX use an unfold to fromObjects or fromUnfold so that we can put any object
349-- | Write a stream of arrays to a handle.
352{-# INLINE fromChunks #-}
353fromChunks :: (MonadIO m, Storable a)
354 => Handle -> SerialT m (Array a) -> m ()
355fromChunks h m = S.mapM_ (liftIO . writeArray h) m
357-- | Write a stream of chunks to standard output.
361{-# INLINE putChunks #-}
362putChunks :: (MonadIO m, Storable a) => SerialT m (Array a) -> m ()
363putChunks = fromChunks stdout
365-- XXX use an unfold so that we can put any type of strings.
366-- | Write a stream of strings to standard output using the supplied encoding.
367-- Output is flushed to the device for each string.
371{-# INLINE putStrings #-}
372putStrings :: MonadAsync m
373 => (SerialT m Char -> SerialT m Word8) -> SerialT m String -> m ()
374putStrings encode = putChunks . S.mapM (IA.fromStream . encode . S.fromList)
376-- XXX use an unfold so that we can put lines from any object
377-- | Write a stream of strings as separate lines to standard output using the
378-- supplied encoding. Output is line buffered i.e. the output is written to the
379-- device as soon as a newline is encountered.
383{-# INLINE putLines #-}
384putLines :: MonadAsync m
385 => (SerialT m Char -> SerialT m Word8) -> SerialT m String -> m ()
386putLines encode = putChunks . S.mapM
387 (\xs -> IA.fromStream $ encode (S.fromList (xs ++ "\n")))
389-- | Write a stream of bytes from standard output.
391-- > putBytes = fromBytes stdout
395{-# INLINE putBytes #-}
396putBytes :: MonadIO m => SerialT m Word8 -> m ()
397putBytes = fromBytes stdout
399-- | @fromChunksWithBufferOf bufsize handle stream@ writes a stream of arrays
400-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
401-- The chunk size is only a maximum and the actual writes could be smaller as
402-- we do not split the arrays to fit exactly to the specified size.
405{-# INLINE fromChunksWithBufferOf #-}
406fromChunksWithBufferOf :: (MonadIO m, Storable a)
407 => Int -> Handle -> SerialT m (Array a) -> m ()
408fromChunksWithBufferOf n h xs = fromChunks h $ AS.compact n xs
410-- | @fromBytesWithBufferOf bufsize handle stream@ writes @stream@ to @handle@
411-- in chunks of @bufsize@. A write is performed to the IO device as soon as we
412-- collect the required input size.
415{-# INLINE fromBytesWithBufferOf #-}
416fromBytesWithBufferOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
417fromBytesWithBufferOf n h m = fromChunks h $ S.arraysOf n m
418-- fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
420-- > write = 'writeWithBufferOf' A.defaultChunkSize
422-- | Write a byte stream to a file handle. Accumulates the input in chunks of
423-- up to 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing.
425-- NOTE: This may perform better than the 'write' fold, you can try this if you
426-- need some extra perf boost.
429{-# INLINE fromBytes #-}
430fromBytes :: MonadIO m => Handle -> SerialT m Word8 -> m ()
431fromBytes = fromBytesWithBufferOf defaultChunkSize
433-- | Write a stream of arrays to a handle. Each array in the stream is written
434-- to the device as a separate IO request.
437{-# INLINE writeChunks #-}
438writeChunks :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
439writeChunks h = FL.drainBy (liftIO . writeArray h)
441{-# INLINE writeChunks2 #-}
442writeChunks2 :: (MonadIO m, Storable a) => Fold2 m Handle (Array a) ()
443writeChunks2 = Fold2 (\h arr -> liftIO $ writeArray h arr >> return h) return (\_ -> return ())
445-- | @writeChunksWithBufferOf bufsize handle@ writes a stream of arrays
446-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
447-- We never split an array, if a single array is bigger than the specified size
448-- it emitted as it is. Multiple arrays are coalesed as long as the total size
449-- remains below the specified size.
452{-# INLINE writeChunksWithBufferOf #-}
453writeChunksWithBufferOf :: (MonadIO m, Storable a)
454 => Int -> Handle -> Fold m (Array a) ()
455writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
457-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
460-- Note that if you use a chunk size less than 8K (GHC's default buffer
461-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
462-- do not want buffering to occur at GHC level as well. Same thing applies to
465-- | @writeWithBufferOf reqSize handle@ writes the input stream to @handle@.
466-- Bytes in the input stream are collected into a buffer until we have a chunk
467-- of @reqSize@ and then written to the IO device.
470{-# INLINE writeWithBufferOf #-}
471writeWithBufferOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
472writeWithBufferOf n h = FL.lchunksOf n (writeNUnsafe n) (writeChunks h)
474{-# INLINE writeWithBufferOf2 #-}
475writeWithBufferOf2 :: MonadIO m => Int -> Fold2 m Handle Word8 ()
476writeWithBufferOf2 n = FL.lchunksOf2 n (writeNUnsafe n) writeChunks2
478-- > write = 'writeWithBufferOf' A.defaultChunkSize
480-- | Write a byte stream to a file handle. Accumulates the input in chunks of
481-- up to 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing
486write :: MonadIO m => Handle -> Fold m Word8 ()
487write = writeWithBufferOf defaultChunkSize
490write2 :: MonadIO m => Fold2 m Handle Word8 ()
491write2 = writeWithBufferOf2 defaultChunkSize
495write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
496write = toHandleWith A.defaultChunkSize
499-- XXX mmap a file into an array. This could be useful for in-place operations
500-- on a file. For example, we can quicksort the contents of a file by mmapping
503-------------------------------------------------------------------------------
504-- IO with encoding/decoding Unicode characters
505-------------------------------------------------------------------------------
509-- > readUtf8 = decodeUtf8 . read
511-- Read a UTF8 encoded stream of unicode characters from a file handle.
514{-# INLINE readUtf8 #-}
515readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
516readUtf8 = decodeUtf8 . read
519-- > writeUtf8 h s = write h $ encodeUtf8 s
521-- Encode a stream of unicode characters to UTF8 and write it to the given file
522-- handle. Default block buffering applies to the writes.
525{-# INLINE writeUtf8 #-}
526writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
527writeUtf8 h s = write h $ encodeUtf8 s
529-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
530-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
531-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
532-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
536{-# INLINE writeUtf8ByLines #-}
537writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
538writeUtf8ByLines = undefined
540-- | Read UTF-8 lines from a file handle and apply the specified fold to each
541-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
544{-# INLINE readLines #-}
545readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
546readLines h f = foldLines (readUtf8 h) f
548-------------------------------------------------------------------------------
549-- Framing on a sequence
550-------------------------------------------------------------------------------
552-- | Read a stream from a file handle and split it into frames delimited by
553-- the specified sequence of elements. The supplied fold is applied on each
557{-# INLINE readFrames #-}
558readFrames :: (IsStream t, MonadIO m, Storable a)
559 => Array a -> Handle -> Fold m a b -> t m b
560readFrames = undefined -- foldFrames . read
562-- | Write a stream to the given file handle buffering up to frames separated
563-- by the given sequence or up to a maximum of @defaultChunkSize@.
566{-# INLINE writeByFrames #-}
567writeByFrames :: (IsStream t, MonadIO m, Storable a)
568 => Array a -> Handle -> t m a -> m ()
569writeByFrames = undefined
571-------------------------------------------------------------------------------
573-------------------------------------------------------------------------------
575-- | Write collecting the input in sessions of n seconds or if chunkSize
577{-# INLINE writeByChunksOrSessionsOf #-}
578writeByChunksOrSessionsOf :: MonadIO m
579 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
580writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
582-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
584{-# INLINE writeBySessionsOf #-}
585writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
586writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
588-------------------------------------------------------------------------------
589-- Random Access IO (Seek)
590-------------------------------------------------------------------------------
592-- XXX handles could be shared, so we may not want to use the handle state at
593-- all for these APIs. we can use pread and pwrite instead. On windows we will
594-- need to use readFile/writeFile with an offset argument.
596-------------------------------------------------------------------------------
598-- | Read the element at the given index treating the file as an array.
601{-# INLINE readIndex #-}
602readIndex :: Storable a => Handle -> Int -> Maybe a
603readIndex arr i = undefined
605-- NOTE: To represent a range to read we have chosen (start, size) instead of
606-- (start, end). This helps in removing the ambiguity of whether "end" is
607-- included in the range or not.
609-- We could avoid specifying the range to be read and instead use "take size"
610-- on the stream, but it may end up reading more and then consume it partially.
612-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
613-- from @handle@ starting at the offset @pos@ from the beginning of the file.
615-- Reads are performed in chunks of size @chunkSize@. For block devices, to
616-- avoid reading partial blocks @chunkSize@ must align with the block size of
617-- the underlying device. If the underlying block size is unknown, it is a good
618-- idea to keep it a multiple 4KiB. This API ensures that the start of each
619-- chunk is aligned with @chunkSize@ from second chunk onwards.
621{-# INLINE readSliceWith #-}
622readSliceWith :: (IsStream t, MonadIO m, Storable a)
623 => Int -> Handle -> Int -> Int -> t m a
624readSliceWith chunkSize h pos len = undefined
626-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
627-- at index @i@ and reading up to @count@ elements in the forward direction
628-- ending at the index @i + count - 1@.
631{-# INLINE readSlice #-}
632readSlice :: (IsStream t, MonadIO m, Storable a)
633 => Handle -> Int -> Int -> t m a
634readSlice = readSliceWith A.defaultChunkSize
636-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
637-- at index @i@ and reading up to @count@ elements in the reverse direction
638-- ending at the index @i - count + 1@.
641{-# INLINE readSliceRev #-}
642readSliceRev :: (IsStream t, MonadIO m, Storable a)
643 => Handle -> Int -> Int -> t m a
644readSliceRev h i count = undefined
646-- | Write the given element at the given index in the file.
649{-# INLINE writeIndex #-}
650writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
651writeIndex h i a = undefined
653-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
654-- starting at index @i@ and writing up to @count@ elements in the forward
655-- direction ending at the index @i + count - 1@.
658{-# INLINE writeSlice #-}
659writeSlice :: (IsStream t, Monad m, Storable a)
660 => Handle -> Int -> Int -> t m a -> m ()
661writeSlice h i len s = undefined
663-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
664-- starting at index @i@ and writing up to @count@ elements in the reverse
665-- direction ending at the index @i - count + 1@.
668{-# INLINE writeSliceRev #-}
669writeSliceRev :: (IsStream t, Monad m, Storable a)
670 => Handle -> Int -> Int -> t m a -> m ()
671writeSliceRev 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