2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
10-- Module : Streamly.Internal.FileSystem.Handle
11-- Copyright : (c) 2018 Composewell Technologies
14-- Maintainer : streamly@composewell.com
15-- Stability : experimental
18module Streamly.Internal.FileSystem.Handle
20 -- ** Read from Handle
38 -- Byte stream write (Folds)
45 -- Byte stream write (Streams)
47 , fromStreamInChunksOf
52 , writeArraysInChunksOf
54 -- -- * Array stream Write
56 , fromStreamArraysInChunksOf
58 -- -- * Random Access (Seek)
59 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
60 -- files that have random access or seek capability. This type of devices
61 -- include disks, files, memory devices and exclude terminals, pipes,
67 -- , readAt -- read from a given position to th end of file
68 -- , readSliceArrayUpto
74 -- , writeAt -- start writing at the given position
79import Control.Monad.IO.Class (MonadIO(..))
80import Data.Word (Word8)
81import Foreign.ForeignPtr (withForeignPtr)
82import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
83import Foreign.Ptr (minusPtr, plusPtr)
84import Foreign.Storable (Storable(..))
85import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
86import System.IO (Handle, hGetBufSome, hPutBuf)
87import Prelude hiding (read)
89import Streamly.Data.Fold (Fold)
90import Streamly.Internal.Data.Unfold.Types (Unfold(..))
91import Streamly.Internal.Memory.Array.Types
92 (Array(..), writeNUnsafe, defaultChunkSize, shrinkToFit,
94import Streamly.Streams.Serial (SerialT)
95import Streamly.Streams.StreamK.Type (IsStream, mkStream)
96-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
98import qualified Streamly.Data.Fold as FL
99import qualified Streamly.Internal.Data.Fold.Types as FL
100import qualified Streamly.Internal.Data.Unfold as UF
101import qualified Streamly.Internal.Memory.ArrayStream as AS
102import qualified Streamly.Internal.Prelude as S
103import qualified Streamly.Memory.Array as A
104import qualified Streamly.Streams.StreamD.Type as D
106-------------------------------------------------------------------------------
108-------------------------------------------------------------------------------
110-- The following references may be useful to build an understanding about the
113-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
114-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
115-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
116-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
117-- https://www.w3.org/TR/FileAPI/ for http file API.
119-------------------------------------------------------------------------------
121-------------------------------------------------------------------------------
123-- | Read a 'ByteArray' from a file handle. If no data is available on the
124-- handle it blocks until some data becomes available. If data is available
125-- then it immediately returns that data without blocking. It reads a maximum
126-- of up to the size requested.
127{-# INLINABLE readArrayUpto #-}
128readArrayUpto :: Int -> Handle -> IO (Array Word8)
129readArrayUpto size h = do
130 ptr <- mallocPlainForeignPtrBytes size
131 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
132 withForeignPtr ptr $ \p -> do
133 n <- hGetBufSome h p size
136 , aEnd = p `plusPtr` n
137 , aBound = p `plusPtr` size
139 -- XXX shrink only if the diff is significant
142-------------------------------------------------------------------------------
143-- Stream of Arrays IO
144-------------------------------------------------------------------------------
146-- | @toStreamArraysOf size h@ reads a stream of arrays from file handle @h@.
147-- The maximum size of a single array is specified by @size@. The actual size
148-- read may be less than or equal to @size@.
149{-# INLINABLE _toStreamArraysOf #-}
150_toStreamArraysOf :: (IsStream t, MonadIO m)
151 => Int -> Handle -> t m (Array Word8)
152_toStreamArraysOf size h = go
154 -- XXX use cons/nil instead
155 go = mkStream $ \_ yld _ stp -> do
156 arr <- liftIO $ readArrayUpto size h
161-- | @toStreamArraysOf size handle@ reads a stream of arrays from the file
162-- handle @handle@. The maximum size of a single array is limited to @size@.
163-- The actual size read may be less than or equal to @size@.
166{-# INLINE_NORMAL toStreamArraysOf #-}
167toStreamArraysOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
168toStreamArraysOf size h = D.fromStreamD (D.Stream step ())
170 {-# INLINE_LATE step #-}
172 arr <- liftIO $ readArrayUpto size h
178{-# INLINE_NORMAL readArraysOf #-}
179readArraysOf :: MonadIO m => Unfold m (Int, Handle) (Array Word8)
180readArraysOf = Unfold step return
182 {-# INLINE_LATE step #-}
184 arr <- liftIO $ readArrayUpto size h
188 _ -> D.Yield arr (size, h)
190-- XXX read 'Array a' instead of Word8
192-- | @toStreamArrays handle@ reads a stream of arrays from the specified file
193-- handle. The maximum size of a single array is limited to
194-- @defaultChunkSize@. The actual size read may be less than or equal to
195-- @defaultChunkSize@.
197-- > toStreamArrays = toStreamArraysOf defaultChunkSize
200{-# INLINE toStreamArrays #-}
201toStreamArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
202toStreamArrays = toStreamArraysOf defaultChunkSize
204-------------------------------------------------------------------------------
205-- Read File to Stream
206-------------------------------------------------------------------------------
208-- TODO for concurrent streams implement readahead IO. We can send multiple
209-- read requests at the same time. For serial case we can use async IO. We can
210-- also control the read throughput in mbps or IOPS.
212-- | @readInChunksOf@ unfolds @(chunksize, handle)@ into a byte stream, reads
213-- are performed in chunks of up to @chunkSize@.
216{-# INLINE readInChunksOf #-}
217readInChunksOf :: MonadIO m => Unfold m (Int, Handle) Word8
218readInChunksOf = UF.concat readArraysOf A.read
220-- | @toStreamInChunksOf chunkSize handle@ reads a byte stream from a file
221-- handle, reads are performed in chunks of up to @chunkSize@.
224{-# INLINE toStreamInChunksOf #-}
225toStreamInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
226toStreamInChunksOf chunkSize h = AS.concat $ toStreamArraysOf chunkSize h
229-- Generate a stream of elements of the given type from a file 'Handle'.
230-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
232-- > read = 'readInChunksOf' A.defaultChunkSize
233-- | Unfolds a file handle into a byte stream.
237read :: MonadIO m => Unfold m Handle Word8
238read = UF.first readInChunksOf defaultChunkSize
240-- | Generate a byte stream from a file 'Handle'.
243{-# INLINE toStream #-}
244toStream :: (IsStream t, MonadIO m) => Handle -> t m Word8
245toStream = AS.concat . toStreamArrays
247-------------------------------------------------------------------------------
249-------------------------------------------------------------------------------
251-------------------------------------------------------------------------------
253-------------------------------------------------------------------------------
255-- | Write an 'Array' to a file handle.
258{-# INLINABLE writeArray #-}
259writeArray :: Storable a => Handle -> Array a -> IO ()
260writeArray _ arr | A.length arr == 0 = return ()
261writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
264 let p = unsafeForeignPtrToPtr aStart
267-------------------------------------------------------------------------------
268-- Stream of Arrays IO
269-------------------------------------------------------------------------------
271-------------------------------------------------------------------------------
273-------------------------------------------------------------------------------
275-- | Write a stream of arrays to a handle.
278{-# INLINE fromStreamArrays #-}
279fromStreamArrays :: (MonadIO m, Storable a)
280 => Handle -> SerialT m (Array a) -> m ()
281fromStreamArrays h m = S.mapM_ (liftIO . writeArray h) m
283-- | @fromStreamArraysInChunksOf chunkSize handle stream@ writes a stream of arrays
284-- to @handle@ after coalescing the adjacent arrays in chunks of @chunkSize@.
285-- The chunk size is only a maximum and the actual writes could be smaller as
286-- we do not split the arrays to fit exactly to the specified size.
289{-# INLINE fromStreamArraysInChunksOf #-}
290fromStreamArraysInChunksOf :: (MonadIO m, Storable a)
291 => Int -> Handle -> SerialT m (Array a) -> m ()
292fromStreamArraysInChunksOf n h xs = fromStreamArrays h $ AS.compact n xs
294-- | @fromStreamInChunksOf chunkSize handle stream@ writes @stream@ to @handle@ in
295-- chunks of @chunkSize@. A write is performed to the IO device as soon as we
296-- collect the required input size.
299{-# INLINE fromStreamInChunksOf #-}
300fromStreamInChunksOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
301fromStreamInChunksOf n h m = fromStreamArrays h $ S.arraysOf n m
302-- fromStreamInChunksOf n h m = fromStreamArrays h $ AS.arraysOf n m
304-- > write = 'writeInChunksOf' A.defaultChunkSize
306-- | Write a byte stream to a file handle. Accumulates the input in chunks of
307-- up to 'A.defaultChunkSize' before writing.
309-- NOTE: This may perform better than the 'write' fold, you can try this if you
310-- need some extra perf boost.
313{-# INLINE fromStream #-}
314fromStream :: MonadIO m => Handle -> SerialT m Word8 -> m ()
315fromStream = fromStreamInChunksOf defaultChunkSize
317-- | Write a stream of arrays to a handle.
320{-# INLINE writeArrays #-}
321writeArrays :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
322writeArrays h = FL.drainBy (liftIO . writeArray h)
324-- | @writeArraysInChunksOf chunkSize handle@ writes a stream of arrays
325-- to @handle@ after coalescing the adjacent arrays in chunks of @chunkSize@.
326-- We never split an array, if a single array is bigger than the specified size
327-- it emitted as it is. Multiple arrays are coalesed as long as the total size
328-- remains below the specified size.
331{-# INLINE writeArraysInChunksOf #-}
332writeArraysInChunksOf :: (MonadIO m, Storable a)
333 => Int -> Handle -> Fold m (Array a) ()
334writeArraysInChunksOf n h = lpackArraysChunksOf n (writeArrays h)
336-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
339-- Note that if you use a chunk size less than 8K (GHC's default buffer
340-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
341-- do not want buffering to occur at GHC level as well. Same thing applies to
344-- | @writeInChunksOf chunkSize handle@ writes the input stream to @handle@ in
345-- chunks of @chunkSize@. A write is performed to the IO device as soon as we
346-- collect the required input size.
349{-# INLINE writeInChunksOf #-}
350writeInChunksOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
351writeInChunksOf n h = FL.lchunksOf n (writeNUnsafe n) (writeArrays h)
353-- > write = 'writeInChunksOf' A.defaultChunkSize
355-- | Write a byte stream to a file handle. Accumulates the input in chunks of
356-- up to 'A.defaultChunkSize' before writing.
360write :: MonadIO m => Handle -> Fold m Word8 ()
361write = writeInChunksOf defaultChunkSize
365write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
366write = toHandleWith A.defaultChunkSize
369-- XXX mmap a file into an array. This could be useful for in-place operations
370-- on a file. For example, we can quicksort the contents of a file by mmapping
373-------------------------------------------------------------------------------
374-- IO with encoding/decoding Unicode characters
375-------------------------------------------------------------------------------
379-- > readUtf8 = decodeUtf8 . read
381-- Read a UTF8 encoded stream of unicode characters from a file handle.
384{-# INLINE readUtf8 #-}
385readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
386readUtf8 = decodeUtf8 . read
389-- > writeUtf8 h s = write h $ encodeUtf8 s
391-- Encode a stream of unicode characters to UTF8 and write it to the given file
392-- handle. Default block buffering applies to the writes.
395{-# INLINE writeUtf8 #-}
396writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
397writeUtf8 h s = write h $ encodeUtf8 s
399-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
400-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
401-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
402-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
406{-# INLINE writeUtf8ByLines #-}
407writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
408writeUtf8ByLines = undefined
410-- | Read UTF-8 lines from a file handle and apply the specified fold to each
411-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
414{-# INLINE readLines #-}
415readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
416readLines h f = foldLines (readUtf8 h) f
418-------------------------------------------------------------------------------
419-- Framing on a sequence
420-------------------------------------------------------------------------------
422-- | Read a stream from a file handle and split it into frames delimited by
423-- the specified sequence of elements. The supplied fold is applied on each
427{-# INLINE readFrames #-}
428readFrames :: (IsStream t, MonadIO m, Storable a)
429 => Array a -> Handle -> Fold m a b -> t m b
430readFrames = undefined -- foldFrames . read
432-- | Write a stream to the given file handle buffering up to frames separated
433-- by the given sequence or up to a maximum of @defaultChunkSize@.
436{-# INLINE writeByFrames #-}
437writeByFrames :: (IsStream t, MonadIO m, Storable a)
438 => Array a -> Handle -> t m a -> m ()
439writeByFrames = undefined
441-------------------------------------------------------------------------------
443-------------------------------------------------------------------------------
445-- | Write collecting the input in sessions of n seconds or if chunkSize
447{-# INLINE writeByChunksOrSessionsOf #-}
448writeByChunksOrSessionsOf :: MonadIO m
449 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
450writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
452-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
454{-# INLINE writeBySessionsOf #-}
455writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
456writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
458-------------------------------------------------------------------------------
459-- Random Access IO (Seek)
460-------------------------------------------------------------------------------
462-- XXX handles could be shared, so we may not want to use the handle state at
463-- all for these APIs. we can use pread and pwrite instead. On windows we will
464-- need to use readFile/writeFile with an offset argument.
466-------------------------------------------------------------------------------
468-- | Read the element at the given index treating the file as an array.
471{-# INLINE readIndex #-}
472readIndex :: Storable a => Handle -> Int -> Maybe a
473readIndex arr i = undefined
475-- NOTE: To represent a range to read we have chosen (start, size) instead of
476-- (start, end). This helps in removing the ambiguity of whether "end" is
477-- included in the range or not.
479-- We could avoid specifying the range to be read and instead use "take size"
480-- on the stream, but it may end up reading more and then consume it partially.
482-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
483-- from @handle@ starting at the offset @pos@ from the beginning of the file.
485-- Reads are performed in chunks of size @chunkSize@. For block devices, to
486-- avoid reading partial blocks @chunkSize@ must align with the block size of
487-- the underlying device. If the underlying block size is unknown, it is a good
488-- idea to keep it a multiple 4KiB. This API ensures that the start of each
489-- chunk is aligned with @chunkSize@ from second chunk onwards.
491{-# INLINE readSliceWith #-}
492readSliceWith :: (IsStream t, MonadIO m, Storable a)
493 => Int -> Handle -> Int -> Int -> t m a
494readSliceWith chunkSize h pos len = undefined
496-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
497-- at index @i@ and reading up to @count@ elements in the forward direction
498-- ending at the index @i + count - 1@.
501{-# INLINE readSlice #-}
502readSlice :: (IsStream t, MonadIO m, Storable a)
503 => Handle -> Int -> Int -> t m a
504readSlice = readSliceWith A.defaultChunkSize
506-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
507-- at index @i@ and reading up to @count@ elements in the reverse direction
508-- ending at the index @i - count + 1@.
511{-# INLINE readSliceRev #-}
512readSliceRev :: (IsStream t, MonadIO m, Storable a)
513 => Handle -> Int -> Int -> t m a
514readSliceRev h i count = undefined
516-- | Write the given element at the given index in the file.
519{-# INLINE writeIndex #-}
520writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
521writeIndex h i a = undefined
523-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
524-- starting at index @i@ and writing up to @count@ elements in the forward
525-- direction ending at the index @i + count - 1@.
528{-# INLINE writeSlice #-}
529writeSlice :: (IsStream t, Monad m, Storable a)
530 => Handle -> Int -> Int -> t m a -> m ()
531writeSlice h i len s = undefined
533-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
534-- starting at index @i@ and writing up to @count@ elements in the reverse
535-- direction ending at the index @i - count + 1@.
538{-# INLINE writeSliceRev #-}
539writeSliceRev :: (IsStream t, Monad m, Storable a)
540 => Handle -> Int -> Int -> t m a -> m ()
541writeSliceRev 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