1{-# OPTIONS_HADDOCK hide #-}
3{-# LANGUAGE BangPatterns #-}
4{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE MagicHash #-}
6{-# LANGUAGE RecordWildCards #-}
7{-# LANGUAGE UnboxedTuples #-}
12-- Module : Streamly.Internal.FileSystem.Handle
13-- Copyright : (c) 2018 Composewell Technologies
16-- Maintainer : streamly@composewell.com
17-- Stability : experimental
20module Streamly.Internal.FileSystem.Handle
22 -- ** Read from Handle
37 , readChunksWithBufferOf
39 , toChunksWithBufferOf
44 -- Byte stream write (Folds)
53 -- Byte stream write (Streams)
55 , fromBytesWithBufferOf
60 , writeChunksWithBufferOf
62 -- -- * Array stream Write
63 , fromChunksWithBufferOf
70 -- -- * Random Access (Seek)
71 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
72 -- files that have random access or seek capability. This type of devices
73 -- include disks, files, memory devices and exclude terminals, pipes,
76 -- XXX need to decide whether to use readFromStepN style or readFromThenTo
77 -- style. The latter is consistent with list enumeration. The former may be
78 -- more unambiguous and it is easier and clearer to specify 0 elements.
80 -- We can also generate the request pattern using a funciton.
83 -- , readFrom -- read from a given position to the end of file
84 -- , readFromRev -- read from a given position the beginning of file
85 -- , readTo -- read from beginning up to the given position
86 -- , readToRev -- read from end to the given position in file
92 -- , readChunksFromToWithBufferOf
93 -- , readChunksFromThenToWithBufferOf
96 -- , writeFrom -- start writing at the given position
98 -- , writeTo -- write from beginning up to the given position
104 -- , writeChunksFromTo
105 -- , writeChunksFromToWithBufferOf
106 -- , writeChunksFromThenToWithBufferOf
110import Control.Monad.IO.Class (MonadIO(..))
111import Data.Word (Word8)
112import Foreign.ForeignPtr (withForeignPtr)
113import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
114import Foreign.Ptr (minusPtr, plusPtr)
115import Foreign.Storable (Storable(..))
116import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
117import System.IO (Handle, hGetBufSome, hPutBuf, stdin, stdout)
118import Prelude hiding (read)
120import Streamly (MonadAsync)
121import Streamly.Data.Fold (Fold)
122import Streamly.Internal.Data.Fold.Types (Fold2(..))
123import Streamly.Internal.Data.Unfold.Types (Unfold(..))
124import Streamly.Internal.Memory.Array.Types
125 (Array(..), writeNUnsafe, defaultChunkSize, shrinkToFit,
127import Streamly.Streams.Serial (SerialT)
128import Streamly.Streams.StreamK.Type (IsStream, mkStream)
129-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
131import qualified Streamly.Data.Fold as FL
132import qualified Streamly.Internal.Data.Fold.Types as FL
133import qualified Streamly.Internal.Data.Unfold as UF
134import qualified Streamly.Internal.Memory.Array as IA
135import qualified Streamly.Internal.Memory.ArrayStream as AS
136import qualified Streamly.Internal.Prelude as S
137import qualified Streamly.Memory.Array as A
138import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
140-------------------------------------------------------------------------------
142-------------------------------------------------------------------------------
144-- The following references may be useful to build an understanding about the
147-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
148-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
149-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
150-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
151-- https://www.w3.org/TR/FileAPI/ for http file API.
153-------------------------------------------------------------------------------
155-------------------------------------------------------------------------------
157-- | Read a 'ByteArray' from a file handle. If no data is available on the
158-- handle it blocks until some data becomes available. If data is available
159-- then it immediately returns that data without blocking. It reads a maximum
160-- of up to the size requested.
161{-# INLINABLE readArrayUpto #-}
162readArrayUpto :: Int -> Handle -> IO (Array Word8)
163readArrayUpto size h = do
164 ptr <- mallocPlainForeignPtrBytes size
165 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
166 withForeignPtr ptr $ \p -> do
167 n <- hGetBufSome h p size
170 , aEnd = p `plusPtr` n
171 , aBound = p `plusPtr` size
173 -- XXX shrink only if the diff is significant
176-------------------------------------------------------------------------------
177-- Stream of Arrays IO
178-------------------------------------------------------------------------------
180-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
181-- The maximum size of a single array is specified by @size@. The actual size
182-- read may be less than or equal to @size@.
183{-# INLINABLE _toChunksWithBufferOf #-}
184_toChunksWithBufferOf :: (IsStream t, MonadIO m)
185 => Int -> Handle -> t m (Array Word8)
186_toChunksWithBufferOf size h = go
188 -- XXX use cons/nil instead
189 go = mkStream $ \_ yld _ stp -> do
190 arr <- liftIO $ readArrayUpto size h
195-- | @toChunksWithBufferOf size handle@ reads a stream of arrays from the file
196-- handle @handle@. The maximum size of a single array is limited to @size@.
197-- The actual size read may be less than or equal to @size@.
200{-# INLINE_NORMAL toChunksWithBufferOf #-}
201toChunksWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
202toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
204 {-# INLINE_LATE step #-}
206 arr <- liftIO $ readArrayUpto size h
212-- | Unfold the tuple @(bufsize, handle)@ into a stream of 'Word8' arrays.
213-- Read requests to the IO device are performed using a buffer of size
214-- @bufsize@. The size of an array in the resulting stream is always less than
215-- or equal to @bufsize@.
218{-# INLINE_NORMAL readChunksWithBufferOf #-}
219readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Handle) (Array Word8)
220readChunksWithBufferOf = Unfold step return
222 {-# INLINE_LATE step #-}
224 arr <- liftIO $ readArrayUpto size h
228 _ -> D.Yield arr (size, h)
230-- XXX read 'Array a' instead of Word8
232-- | @toChunks handle@ reads a stream of arrays from the specified file
233-- handle. The maximum size of a single array is limited to
234-- @defaultChunkSize@. The actual size read may be less than or equal to
235-- @defaultChunkSize@.
237-- > toChunks = toChunksWithBufferOf defaultChunkSize
240{-# INLINE toChunks #-}
241toChunks :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
242toChunks = toChunksWithBufferOf defaultChunkSize
244-- | Read a stream of chunks from standard input. The maximum size of a single
245-- chunk is limited to @defaultChunkSize@. The actual size read may be less
246-- than @defaultChunkSize@.
248-- > getChunks = toChunks stdin
252{-# INLINE getChunks #-}
253getChunks :: (IsStream t, MonadIO m) => t m (Array Word8)
254getChunks = toChunks stdin
256-- | Read a stream of bytes from standard input.
258-- > getBytes = toBytes stdin
262{-# INLINE getBytes #-}
263getBytes :: (IsStream t, MonadIO m) => t m Word8
264getBytes = toBytes stdin
266-- | Unfolds a handle into a stream of 'Word8' arrays. Requests to the IO
267-- device are performed using a buffer of size
268-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. The
269-- size of arrays in the resulting stream are therefore less than or equal to
270-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
273{-# INLINE readChunks #-}
274readChunks :: MonadIO m => Unfold m Handle (Array Word8)
275readChunks = UF.supplyFirst readChunksWithBufferOf defaultChunkSize
277-------------------------------------------------------------------------------
278-- Read File to Stream
279-------------------------------------------------------------------------------
281-- TODO for concurrent streams implement readahead IO. We can send multiple
282-- read requests at the same time. For serial case we can use async IO. We can
283-- also control the read throughput in mbps or IOPS.
285-- | Unfolds the tuple @(bufsize, handle)@ into a byte stream, read requests
286-- to the IO device are performed using buffers of @bufsize@.
289{-# INLINE readWithBufferOf #-}
290readWithBufferOf :: MonadIO m => Unfold m (Int, Handle) Word8
291readWithBufferOf = UF.concat readChunksWithBufferOf A.read
293-- | @toBytesWithBufferOf bufsize handle@ reads a byte stream from a file
294-- handle, reads are performed in chunks of up to @bufsize@.
297{-# INLINE toBytesWithBufferOf #-}
298toBytesWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
299toBytesWithBufferOf chunkSize h = AS.concat $ toChunksWithBufferOf chunkSize h
302-- Generate a stream of elements of the given type from a file 'Handle'.
303-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
305-- | Unfolds a file handle into a byte stream. IO requests to the device are
306-- performed in sizes of
307-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
311read :: MonadIO m => Unfold m Handle Word8
312read = UF.supplyFirst readWithBufferOf defaultChunkSize
314-- | Generate a byte stream from a file 'Handle'.
317{-# INLINE toBytes #-}
318toBytes :: (IsStream t, MonadIO m) => Handle -> t m Word8
319toBytes = AS.concat . toChunks
321-------------------------------------------------------------------------------
323-------------------------------------------------------------------------------
325-------------------------------------------------------------------------------
327-------------------------------------------------------------------------------
329-- | Write an 'Array' to a file handle.
332{-# INLINABLE writeArray #-}
333writeArray :: Storable a => Handle -> Array a -> IO ()
334writeArray _ arr | A.length arr == 0 = return ()
335writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
338 let p = unsafeForeignPtrToPtr aStart
341-------------------------------------------------------------------------------
342-- Stream of Arrays IO
343-------------------------------------------------------------------------------
345-------------------------------------------------------------------------------
347-------------------------------------------------------------------------------
349-- XXX use an unfold to fromObjects or fromUnfold so that we can put any object
350-- | Write a stream of arrays to a handle.
353{-# INLINE fromChunks #-}
354fromChunks :: (MonadIO m, Storable a)
355 => Handle -> SerialT m (Array a) -> m ()
356fromChunks h m = S.mapM_ (liftIO . writeArray h) m
358-- | Write a stream of chunks to standard output.
362{-# INLINE putChunks #-}
363putChunks :: (MonadIO m, Storable a) => SerialT m (Array a) -> m ()
364putChunks = fromChunks stdout
366-- XXX use an unfold so that we can put any type of strings.
367-- | Write a stream of strings to standard output using the supplied encoding.
368-- Output is flushed to the device for each string.
372{-# INLINE putStrings #-}
373putStrings :: MonadAsync m
374 => (SerialT m Char -> SerialT m Word8) -> SerialT m String -> m ()
375putStrings encode = putChunks . S.mapM (IA.fromStream . encode . S.fromList)
377-- XXX use an unfold so that we can put lines from any object
378-- | Write a stream of strings as separate lines to standard output using the
379-- supplied encoding. Output is line buffered i.e. the output is written to the
380-- device as soon as a newline is encountered.
384{-# INLINE putLines #-}
385putLines :: MonadAsync m
386 => (SerialT m Char -> SerialT m Word8) -> SerialT m String -> m ()
387putLines encode = putChunks . S.mapM
388 (\xs -> IA.fromStream $ encode (S.fromList (xs ++ "\n")))
390-- | Write a stream of bytes from standard output.
392-- > putBytes = fromBytes stdout
396{-# INLINE putBytes #-}
397putBytes :: MonadIO m => SerialT m Word8 -> m ()
398putBytes = fromBytes stdout
400-- | @fromChunksWithBufferOf bufsize handle stream@ writes a stream of arrays
401-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
402-- The chunk size is only a maximum and the actual writes could be smaller as
403-- we do not split the arrays to fit exactly to the specified size.
406{-# INLINE fromChunksWithBufferOf #-}
407fromChunksWithBufferOf :: (MonadIO m, Storable a)
408 => Int -> Handle -> SerialT m (Array a) -> m ()
409fromChunksWithBufferOf n h xs = fromChunks h $ AS.compact n xs
411-- | @fromBytesWithBufferOf bufsize handle stream@ writes @stream@ to @handle@
412-- in chunks of @bufsize@. A write is performed to the IO device as soon as we
413-- collect the required input size.
416{-# INLINE fromBytesWithBufferOf #-}
417fromBytesWithBufferOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
418fromBytesWithBufferOf n h m = fromChunks h $ S.arraysOf n m
419-- fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
421-- > write = 'writeWithBufferOf' A.defaultChunkSize
423-- | Write a byte stream to a file handle. Accumulates the input in chunks of
424-- up to 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing.
426-- NOTE: This may perform better than the 'write' fold, you can try this if you
427-- need some extra perf boost.
430{-# INLINE fromBytes #-}
431fromBytes :: MonadIO m => Handle -> SerialT m Word8 -> m ()
432fromBytes = fromBytesWithBufferOf defaultChunkSize
434-- | Write a stream of arrays to a handle. Each array in the stream is written
435-- to the device as a separate IO request.
438{-# INLINE writeChunks #-}
439writeChunks :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
440writeChunks h = FL.drainBy (liftIO . writeArray h)
442{-# INLINE writeChunks2 #-}
443writeChunks2 :: (MonadIO m, Storable a) => Fold2 m Handle (Array a) ()
444writeChunks2 = Fold2 (\h arr -> liftIO $ writeArray h arr >> return h) return (\_ -> return ())
446-- | @writeChunksWithBufferOf bufsize handle@ writes a stream of arrays
447-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
448-- We never split an array, if a single array is bigger than the specified size
449-- it emitted as it is. Multiple arrays are coalesed as long as the total size
450-- remains below the specified size.
453{-# INLINE writeChunksWithBufferOf #-}
454writeChunksWithBufferOf :: (MonadIO m, Storable a)
455 => Int -> Handle -> Fold m (Array a) ()
456writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
458-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
461-- Note that if you use a chunk size less than 8K (GHC's default buffer
462-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
463-- do not want buffering to occur at GHC level as well. Same thing applies to
466-- | @writeWithBufferOf reqSize handle@ writes the input stream to @handle@.
467-- Bytes in the input stream are collected into a buffer until we have a chunk
468-- of @reqSize@ and then written to the IO device.
471{-# INLINE writeWithBufferOf #-}
472writeWithBufferOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
473writeWithBufferOf n h = FL.lchunksOf n (writeNUnsafe n) (writeChunks h)
475{-# INLINE writeWithBufferOf2 #-}
476writeWithBufferOf2 :: MonadIO m => Int -> Fold2 m Handle Word8 ()
477writeWithBufferOf2 n = FL.lchunksOf2 n (writeNUnsafe n) writeChunks2
479-- > write = 'writeWithBufferOf' A.defaultChunkSize
481-- | Write a byte stream to a file handle. Accumulates the input in chunks of
482-- up to 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing
487write :: MonadIO m => Handle -> Fold m Word8 ()
488write = writeWithBufferOf defaultChunkSize
491write2 :: MonadIO m => Fold2 m Handle Word8 ()
492write2 = writeWithBufferOf2 defaultChunkSize
496write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
497write = toHandleWith A.defaultChunkSize
500-- XXX mmap a file into an array. This could be useful for in-place operations
501-- on a file. For example, we can quicksort the contents of a file by mmapping
504-------------------------------------------------------------------------------
505-- IO with encoding/decoding Unicode characters
506-------------------------------------------------------------------------------
510-- > readUtf8 = decodeUtf8 . read
512-- Read a UTF8 encoded stream of unicode characters from a file handle.
515{-# INLINE readUtf8 #-}
516readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
517readUtf8 = decodeUtf8 . read
520-- > writeUtf8 h s = write h $ encodeUtf8 s
522-- Encode a stream of unicode characters to UTF8 and write it to the given file
523-- handle. Default block buffering applies to the writes.
526{-# INLINE writeUtf8 #-}
527writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
528writeUtf8 h s = write h $ encodeUtf8 s
530-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
531-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
532-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
533-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
537{-# INLINE writeUtf8ByLines #-}
538writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
539writeUtf8ByLines = undefined
541-- | Read UTF-8 lines from a file handle and apply the specified fold to each
542-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
545{-# INLINE readLines #-}
546readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
547readLines h f = foldLines (readUtf8 h) f
549-------------------------------------------------------------------------------
550-- Framing on a sequence
551-------------------------------------------------------------------------------
553-- | Read a stream from a file handle and split it into frames delimited by
554-- the specified sequence of elements. The supplied fold is applied on each
558{-# INLINE readFrames #-}
559readFrames :: (IsStream t, MonadIO m, Storable a)
560 => Array a -> Handle -> Fold m a b -> t m b
561readFrames = undefined -- foldFrames . read
563-- | Write a stream to the given file handle buffering up to frames separated
564-- by the given sequence or up to a maximum of @defaultChunkSize@.
567{-# INLINE writeByFrames #-}
568writeByFrames :: (IsStream t, MonadIO m, Storable a)
569 => Array a -> Handle -> t m a -> m ()
570writeByFrames = undefined
572-------------------------------------------------------------------------------
574-------------------------------------------------------------------------------
576-- | Write collecting the input in sessions of n seconds or if chunkSize
578{-# INLINE writeByChunksOrSessionsOf #-}
579writeByChunksOrSessionsOf :: MonadIO m
580 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
581writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
583-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
585{-# INLINE writeBySessionsOf #-}
586writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
587writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
589-------------------------------------------------------------------------------
590-- Random Access IO (Seek)
591-------------------------------------------------------------------------------
593-- XXX handles could be shared, so we may not want to use the handle state at
594-- all for these APIs. we can use pread and pwrite instead. On windows we will
595-- need to use readFile/writeFile with an offset argument.
597-------------------------------------------------------------------------------
599-- | Read the element at the given index treating the file as an array.
602{-# INLINE readIndex #-}
603readIndex :: Storable a => Handle -> Int -> Maybe a
604readIndex arr i = undefined
606-- NOTE: To represent a range to read we have chosen (start, size) instead of
607-- (start, end). This helps in removing the ambiguity of whether "end" is
608-- included in the range or not.
610-- We could avoid specifying the range to be read and instead use "take size"
611-- on the stream, but it may end up reading more and then consume it partially.
613-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
614-- from @handle@ starting at the offset @pos@ from the beginning of the file.
616-- Reads are performed in chunks of size @chunkSize@. For block devices, to
617-- avoid reading partial blocks @chunkSize@ must align with the block size of
618-- the underlying device. If the underlying block size is unknown, it is a good
619-- idea to keep it a multiple 4KiB. This API ensures that the start of each
620-- chunk is aligned with @chunkSize@ from second chunk onwards.
622{-# INLINE readSliceWith #-}
623readSliceWith :: (IsStream t, MonadIO m, Storable a)
624 => Int -> Handle -> Int -> Int -> t m a
625readSliceWith chunkSize h pos len = undefined
627-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
628-- at index @i@ and reading up to @count@ elements in the forward direction
629-- ending at the index @i + count - 1@.
632{-# INLINE readSlice #-}
633readSlice :: (IsStream t, MonadIO m, Storable a)
634 => Handle -> Int -> Int -> t m a
635readSlice = readSliceWith A.defaultChunkSize
637-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
638-- at index @i@ and reading up to @count@ elements in the reverse direction
639-- ending at the index @i - count + 1@.
642{-# INLINE readSliceRev #-}
643readSliceRev :: (IsStream t, MonadIO m, Storable a)
644 => Handle -> Int -> Int -> t m a
645readSliceRev h i count = undefined
647-- | Write the given element at the given index in the file.
650{-# INLINE writeIndex #-}
651writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
652writeIndex h i a = undefined
654-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
655-- starting at index @i@ and writing up to @count@ elements in the forward
656-- direction ending at the index @i + count - 1@.
659{-# INLINE writeSlice #-}
660writeSlice :: (IsStream t, Monad m, Storable a)
661 => Handle -> Int -> Int -> t m a -> m ()
662writeSlice h i len s = undefined
664-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
665-- starting at index @i@ and writing up to @count@ elements in the reverse
666-- direction ending at the index @i - count + 1@.
669{-# INLINE writeSliceRev #-}
670writeSliceRev :: (IsStream t, Monad m, Storable a)
671 => Handle -> Int -> Int -> t m a -> m ()
672writeSliceRev 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