on f8f323a help sign in
542 lines 20 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
7#include "inline.hs"
9-- |
10-- Module : Streamly.Internal.FileSystem.Handle
11-- Copyright : (c) 2018 Composewell Technologies
12--
13-- License : BSD3
14-- Maintainer : streamly@composewell.com
15-- Stability : experimental
16-- Portability : GHC
18module Streamly.Internal.FileSystem.Handle
19 (
20 -- ** Read from Handle
21 read
22 -- , readUtf8
23 -- , readLines
24 -- , readFrames
25 , readInChunksOf
27 , toStream
28 , toStreamInChunksOf
30 -- -- * Array Read
31 -- , readArrayUpto
32 -- , readArrayOf
34 , toStreamArraysOf
35 , toStreamArrays
37 -- ** Write to Handle
38 -- Byte stream write (Folds)
39 , write
40 -- , writeUtf8
41 -- , writeUtf8ByLines
42 -- , writeByFrames
43 , writeInChunksOf
45 -- Byte stream write (Streams)
46 , fromStream
47 , fromStreamInChunksOf
49 -- -- * Array Write
50 , writeArray
51 , writeArrays
52 , writeArraysInChunksOf
54 -- -- * Array stream Write
55 , fromStreamArrays
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,
62 -- sockets and fifos.
63 --
64 -- , readIndex
65 -- , readSlice
66 -- , readSliceRev
67 -- , readAt -- read from a given position to th end of file
68 -- , readSliceArrayUpto
69 -- , readSliceArrayOf
71 -- , writeIndex
72 -- , writeSlice
73 -- , writeSliceRev
74 -- , writeAt -- start writing at the given position
75 -- , writeSliceArray
76 )
77where
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,
93 lpackArraysChunksOf)
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-------------------------------------------------------------------------------
107-- References
108-------------------------------------------------------------------------------
109--
110-- The following references may be useful to build an understanding about the
111-- file API design:
112--
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-------------------------------------------------------------------------------
120-- Array IO (Input)
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
134 let v = Array
135 { aStart = ptr
136 , aEnd = p `plusPtr` n
137 , aBound = p `plusPtr` size
138 }
139 -- XXX shrink only if the diff is significant
140 shrinkToFit v
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
153 where
154 -- XXX use cons/nil instead
155 go = mkStream $ \_ yld _ stp -> do
156 arr <- liftIO $ readArrayUpto size h
157 if A.length arr == 0
158 then stp
159 else yld arr go
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@.
164--
165-- @since 0.7.0
166{-# INLINE_NORMAL toStreamArraysOf #-}
167toStreamArraysOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
168toStreamArraysOf size h = D.fromStreamD (D.Stream step ())
169 where
170 {-# INLINE_LATE step #-}
171 step _ _ = do
172 arr <- liftIO $ readArrayUpto size h
173 return $
174 case A.length arr of
175 0 -> D.Stop
176 _ -> D.Yield arr ()
178{-# INLINE_NORMAL readArraysOf #-}
179readArraysOf :: MonadIO m => Unfold m (Int, Handle) (Array Word8)
180readArraysOf = Unfold step return
181 where
182 {-# INLINE_LATE step #-}
183 step (size, h) = do
184 arr <- liftIO $ readArrayUpto size h
185 return $
186 case A.length arr of
187 0 -> D.Stop
188 _ -> D.Yield arr (size, h)
190-- XXX read 'Array a' instead of Word8
191--
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@.
196--
197-- > toStreamArrays = toStreamArraysOf defaultChunkSize
198--
199-- @since 0.7.0
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@.
214--
215-- @since 0.7.0
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@.
222--
223-- /Internal/
224{-# INLINE toStreamInChunksOf #-}
225toStreamInChunksOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
226toStreamInChunksOf chunkSize h = AS.concat $ toStreamArraysOf chunkSize h
228-- TODO
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
231--
232-- > read = 'readInChunksOf' A.defaultChunkSize
233-- | Unfolds a file handle into a byte stream.
234--
235-- @since 0.7.0
236{-# INLINE read #-}
237read :: MonadIO m => Unfold m Handle Word8
238read = UF.first readInChunksOf defaultChunkSize
240-- | Generate a byte stream from a file 'Handle'.
241--
242-- /Internal/
243{-# INLINE toStream #-}
244toStream :: (IsStream t, MonadIO m) => Handle -> t m Word8
245toStream = AS.concat . toStreamArrays
247-------------------------------------------------------------------------------
248-- Writing
249-------------------------------------------------------------------------------
251-------------------------------------------------------------------------------
252-- Array IO (output)
253-------------------------------------------------------------------------------
255-- | Write an 'Array' to a file handle.
256--
257-- @since 0.7.0
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
262 where
263 aLen =
264 let p = unsafeForeignPtrToPtr aStart
265 in aEnd `minusPtr` p
267-------------------------------------------------------------------------------
268-- Stream of Arrays IO
269-------------------------------------------------------------------------------
271-------------------------------------------------------------------------------
272-- Writing
273-------------------------------------------------------------------------------
275-- | Write a stream of arrays to a handle.
276--
277-- @since 0.7.0
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.
287--
288-- @since 0.7.0
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.
297--
298-- @since 0.7.0
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
305--
306-- | Write a byte stream to a file handle. Accumulates the input in chunks of
307-- up to 'A.defaultChunkSize' before writing.
308--
309-- NOTE: This may perform better than the 'write' fold, you can try this if you
310-- need some extra perf boost.
311--
312-- @since 0.7.0
313{-# INLINE fromStream #-}
314fromStream :: MonadIO m => Handle -> SerialT m Word8 -> m ()
315fromStream = fromStreamInChunksOf defaultChunkSize
317-- | Write a stream of arrays to a handle.
318--
319-- @since 0.7.0
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.
329--
330-- @since 0.7.0
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.
337--
338-- XXX test this
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
342-- writes as well.
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.
347--
348-- @since 0.7.0
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
354--
355-- | Write a byte stream to a file handle. Accumulates the input in chunks of
356-- up to 'A.defaultChunkSize' before writing.
357--
358-- @since 0.7.0
359{-# INLINE write #-}
360write :: MonadIO m => Handle -> Fold m Word8 ()
361write = writeInChunksOf defaultChunkSize
363{-
364{-# INLINE write #-}
365write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
366write = toHandleWith A.defaultChunkSize
367-}
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
371-- it.
373-------------------------------------------------------------------------------
374-- IO with encoding/decoding Unicode characters
375-------------------------------------------------------------------------------
377{-
378-- |
379-- > readUtf8 = decodeUtf8 . read
380--
381-- Read a UTF8 encoded stream of unicode characters from a file handle.
382--
383-- @since 0.7.0
384{-# INLINE readUtf8 #-}
385readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
386readUtf8 = decodeUtf8 . read
388-- |
389-- > writeUtf8 h s = write h $ encodeUtf8 s
390--
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.
393--
394-- @since 0.7.0
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'
403-- option.
404--
405-- @since 0.7.0
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.
412--
413-- @since 0.7.0
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
424-- frame.
425--
426-- @since 0.7.0
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@.
434--
435-- @since 0.7.0
436{-# INLINE writeByFrames #-}
437writeByFrames :: (IsStream t, MonadIO m, Storable a)
438 => Array a -> Handle -> t m a -> m ()
439writeByFrames = undefined
441-------------------------------------------------------------------------------
442-- Framing by time
443-------------------------------------------------------------------------------
445-- | Write collecting the input in sessions of n seconds or if chunkSize
446-- gets exceeded.
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
453-- gets exceeded.
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.
469--
470-- @since 0.7.0
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.
478--
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.
484--
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.
490--
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@.
499--
500-- @since 0.7.0
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@.
509--
510-- @since 0.7.0
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.
517--
518-- @since 0.7.0
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@.
526--
527-- @since 0.7.0
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@.
536--
537-- @since 0.7.0
538{-# INLINE writeSliceRev #-}
539writeSliceRev :: (IsStream t, Monad m, Storable a)
540 => Handle -> Int -> Int -> t m a -> m ()
541writeSliceRev arr i len s = undefined
542-}