on b7c094e help sign in
606 lines 22 kB history raw
1{-# OPTIONS_HADDOCK hide #-}
2{-# LANGUAGE CPP #-}
3{-# LANGUAGE BangPatterns #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
8#include "inline.hs"
10-- |
11-- Module : Streamly.Internal.FileSystem.Handle
12-- Copyright : (c) 2018 Composewell Technologies
13--
14-- License : BSD3
15-- Maintainer : streamly@composewell.com
16-- Stability : experimental
17-- Portability : GHC
19module Streamly.Internal.FileSystem.Handle
20 (
21 -- ** Read from Handle
22 read
23 -- , readUtf8
24 -- , readLines
25 -- , readFrames
26 , readWithBufferOf
28 , toBytes
29 , toBytesWithBufferOf
31 -- -- * Array Read
32 -- , readArrayUpto
33 -- , readArrayOf
34 , readChunks
35 , readChunksWithBufferOf
37 , toChunksWithBufferOf
38 , toChunks
39 , getChunks
41 -- ** Write to Handle
42 -- Byte stream write (Folds)
43 , write
44 -- , writeUtf8
45 -- , writeUtf8ByLines
46 -- , writeByFrames
47 , writeWithBufferOf
49 -- Byte stream write (Streams)
50 , fromBytes
51 , fromBytesWithBufferOf
53 -- -- * Array Write
54 , writeArray
55 , writeChunks
56 , writeChunksWithBufferOf
58 -- -- * Array stream Write
59 , fromChunksWithBufferOf
60 , fromChunks
61 , putChunks
63 -- -- * Random Access (Seek)
64 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
65 -- files that have random access or seek capability. This type of devices
66 -- include disks, files, memory devices and exclude terminals, pipes,
67 -- sockets and fifos.
68 --
69 -- XXX need to decide whether to use readFromStepN style or readFromThenTo
70 -- style. The latter is consistent with list enumeration. The former may be
71 -- more unambiguous and it is easier and clearer to specify 0 elements.
72 --
73 -- We can also generate the request pattern using a funciton.
74 --
75 -- , readIndex
76 -- , readFrom -- read from a given position to the end of file
77 -- , readFromRev -- read from a given position the beginning of file
78 -- , readTo -- read from beginning up to the given position
79 -- , readToRev -- read from end to the given position in file
80 -- , readFromTo
81 -- , readFromThenTo
83 -- , readChunksFrom
84 -- , readChunksFromTo
85 -- , readChunksFromToWithBufferOf
86 -- , readChunksFromThenToWithBufferOf
88 -- , writeIndex
89 -- , writeFrom -- start writing at the given position
90 -- , writeFromRev
91 -- , writeTo -- write from beginning up to the given position
92 -- , writeToRev
93 -- , writeFromTo
94 -- , writeFromThenTo
95 --
96 -- , writeChunksFrom
97 -- , writeChunksFromTo
98 -- , writeChunksFromToWithBufferOf
99 -- , writeChunksFromThenToWithBufferOf
100 )
101where
103import Control.Monad.IO.Class (MonadIO(..))
104import Data.Word (Word8)
105import Foreign.ForeignPtr (withForeignPtr)
106import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
107import Foreign.Ptr (minusPtr, plusPtr)
108import Foreign.Storable (Storable(..))
109import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
110import System.IO (Handle, hGetBufSome, hPutBuf, stdin, stdout)
111import Prelude hiding (read)
113import Streamly.Data.Fold (Fold)
114import Streamly.Internal.Data.Unfold.Types (Unfold(..))
115import Streamly.Internal.Memory.Array.Types
116 (Array(..), writeNUnsafe, defaultChunkSize, shrinkToFit,
117 lpackArraysChunksOf)
118import Streamly.Streams.Serial (SerialT)
119import Streamly.Streams.StreamK.Type (IsStream, mkStream)
120-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
122import qualified Streamly.Data.Fold as FL
123import qualified Streamly.Internal.Data.Fold.Types as FL
124import qualified Streamly.Internal.Data.Unfold as UF
125import qualified Streamly.Internal.Memory.ArrayStream as AS
126import qualified Streamly.Internal.Prelude as S
127import qualified Streamly.Memory.Array as A
128import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
130-------------------------------------------------------------------------------
131-- References
132-------------------------------------------------------------------------------
133--
134-- The following references may be useful to build an understanding about the
135-- file API design:
136--
137-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
138-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
139-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
140-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
141-- https://www.w3.org/TR/FileAPI/ for http file API.
143-------------------------------------------------------------------------------
144-- Array IO (Input)
145-------------------------------------------------------------------------------
147-- | Read a 'ByteArray' from a file handle. If no data is available on the
148-- handle it blocks until some data becomes available. If data is available
149-- then it immediately returns that data without blocking. It reads a maximum
150-- of up to the size requested.
151{-# INLINABLE readArrayUpto #-}
152readArrayUpto :: Int -> Handle -> IO (Array Word8)
153readArrayUpto size h = do
154 ptr <- mallocPlainForeignPtrBytes size
155 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
156 withForeignPtr ptr $ \p -> do
157 n <- hGetBufSome h p size
158 let v = Array
159 { aStart = ptr
160 , aEnd = p `plusPtr` n
161 , aBound = p `plusPtr` size
162 }
163 -- XXX shrink only if the diff is significant
164 shrinkToFit v
166-------------------------------------------------------------------------------
167-- Stream of Arrays IO
168-------------------------------------------------------------------------------
170-- | @toChunksWithBufferOf size h@ reads a stream of arrays from file handle @h@.
171-- The maximum size of a single array is specified by @size@. The actual size
172-- read may be less than or equal to @size@.
173{-# INLINABLE _toChunksWithBufferOf #-}
174_toChunksWithBufferOf :: (IsStream t, MonadIO m)
175 => Int -> Handle -> t m (Array Word8)
176_toChunksWithBufferOf size h = go
177 where
178 -- XXX use cons/nil instead
179 go = mkStream $ \_ yld _ stp -> do
180 arr <- liftIO $ readArrayUpto size h
181 if A.length arr == 0
182 then stp
183 else yld arr go
185-- | @toChunksWithBufferOf size handle@ reads a stream of arrays from the file
186-- handle @handle@. The maximum size of a single array is limited to @size@.
187-- The actual size read may be less than or equal to @size@.
188--
189-- @since 0.7.0
190{-# INLINE_NORMAL toChunksWithBufferOf #-}
191toChunksWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
192toChunksWithBufferOf size h = D.fromStreamD (D.Stream step ())
193 where
194 {-# INLINE_LATE step #-}
195 step _ _ = do
196 arr <- liftIO $ readArrayUpto size h
197 return $
198 case A.length arr of
199 0 -> D.Stop
200 _ -> D.Yield arr ()
202-- | Unfold the tuple @(bufsize, handle)@ into a stream of 'Word8' arrays.
203-- Read requests to the IO device are performed using a buffer of size
204-- @bufsize@. The size of an array in the resulting stream is always less than
205-- or equal to @bufsize@.
206--
207-- @since 0.7.0
208{-# INLINE_NORMAL readChunksWithBufferOf #-}
209readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Handle) (Array Word8)
210readChunksWithBufferOf = Unfold step return
211 where
212 {-# INLINE_LATE step #-}
213 step (size, h) = do
214 arr <- liftIO $ readArrayUpto size h
215 return $
216 case A.length arr of
217 0 -> D.Stop
218 _ -> D.Yield arr (size, h)
220-- XXX read 'Array a' instead of Word8
221--
222-- | @toChunks handle@ reads a stream of arrays from the specified file
223-- handle. The maximum size of a single array is limited to
224-- @defaultChunkSize@. The actual size read may be less than or equal to
225-- @defaultChunkSize@.
226--
227-- > toChunks = toChunksWithBufferOf defaultChunkSize
228--
229-- @since 0.7.0
230{-# INLINE toChunks #-}
231toChunks :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
232toChunks = toChunksWithBufferOf defaultChunkSize
234-- | Read a stream of chunks from standard input. The maximum size of a single
235-- chunk is limited to @defaultChunkSize@. The actual size read may be less
236-- than @defaultChunkSize@.
237--
238-- > getChunks = toChunks stdin
239--
240-- /Internal/
241--
242{-# INLINE getChunks #-}
243getChunks :: (IsStream t, MonadIO m) => t m (Array Word8)
244getChunks = toChunks stdin
246-- | Unfolds a handle into a stream of 'Word8' arrays. Requests to the IO
247-- device are performed using a buffer of size
248-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. The
249-- size of arrays in the resulting stream are therefore less than or equal to
250-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
251--
252-- @since 0.7.0
253{-# INLINE readChunks #-}
254readChunks :: MonadIO m => Unfold m Handle (Array Word8)
255readChunks = UF.supplyFirst readChunksWithBufferOf defaultChunkSize
257-------------------------------------------------------------------------------
258-- Read File to Stream
259-------------------------------------------------------------------------------
261-- TODO for concurrent streams implement readahead IO. We can send multiple
262-- read requests at the same time. For serial case we can use async IO. We can
263-- also control the read throughput in mbps or IOPS.
265-- | Unfolds the tuple @(bufsize, handle)@ into a byte stream, read requests
266-- to the IO device are performed using buffers of @bufsize@.
267--
268-- @since 0.7.0
269{-# INLINE readWithBufferOf #-}
270readWithBufferOf :: MonadIO m => Unfold m (Int, Handle) Word8
271readWithBufferOf = UF.concat readChunksWithBufferOf A.read
273-- | @toBytesWithBufferOf bufsize handle@ reads a byte stream from a file
274-- handle, reads are performed in chunks of up to @bufsize@.
275--
276-- /Internal/
277{-# INLINE toBytesWithBufferOf #-}
278toBytesWithBufferOf :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
279toBytesWithBufferOf chunkSize h = AS.concat $ toChunksWithBufferOf chunkSize h
281-- TODO
282-- Generate a stream of elements of the given type from a file 'Handle'.
283-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
284--
285-- | Unfolds a file handle into a byte stream. IO requests to the device are
286-- performed in sizes of
287-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'.
288--
289-- @since 0.7.0
290{-# INLINE read #-}
291read :: MonadIO m => Unfold m Handle Word8
292read = UF.supplyFirst readWithBufferOf defaultChunkSize
294-- | Generate a byte stream from a file 'Handle'.
295--
296-- /Internal/
297{-# INLINE toBytes #-}
298toBytes :: (IsStream t, MonadIO m) => Handle -> t m Word8
299toBytes = AS.concat . toChunks
301-------------------------------------------------------------------------------
302-- Writing
303-------------------------------------------------------------------------------
305-------------------------------------------------------------------------------
306-- Array IO (output)
307-------------------------------------------------------------------------------
309-- | Write an 'Array' to a file handle.
310--
311-- @since 0.7.0
312{-# INLINABLE writeArray #-}
313writeArray :: Storable a => Handle -> Array a -> IO ()
314writeArray _ arr | A.length arr == 0 = return ()
315writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
316 where
317 aLen =
318 let p = unsafeForeignPtrToPtr aStart
319 in aEnd `minusPtr` p
321-------------------------------------------------------------------------------
322-- Stream of Arrays IO
323-------------------------------------------------------------------------------
325-------------------------------------------------------------------------------
326-- Writing
327-------------------------------------------------------------------------------
329-- | Write a stream of arrays to a handle.
330--
331-- @since 0.7.0
332{-# INLINE fromChunks #-}
333fromChunks :: (MonadIO m, Storable a)
334 => Handle -> SerialT m (Array a) -> m ()
335fromChunks h m = S.mapM_ (liftIO . writeArray h) m
337-- | Write a stream of chunks to standard output.
338--
339-- /Internal/
340--
341{-# INLINE putChunks #-}
342putChunks :: (MonadIO m, Storable a) => SerialT m (Array a) -> m ()
343putChunks = fromChunks stdout
345-- | @fromChunksWithBufferOf bufsize handle stream@ writes a stream of arrays
346-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
347-- The chunk size is only a maximum and the actual writes could be smaller as
348-- we do not split the arrays to fit exactly to the specified size.
349--
350-- @since 0.7.0
351{-# INLINE fromChunksWithBufferOf #-}
352fromChunksWithBufferOf :: (MonadIO m, Storable a)
353 => Int -> Handle -> SerialT m (Array a) -> m ()
354fromChunksWithBufferOf n h xs = fromChunks h $ AS.compact n xs
356-- | @fromBytesWithBufferOf bufsize handle stream@ writes @stream@ to @handle@
357-- in chunks of @bufsize@. A write is performed to the IO device as soon as we
358-- collect the required input size.
359--
360-- @since 0.7.0
361{-# INLINE fromBytesWithBufferOf #-}
362fromBytesWithBufferOf :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
363fromBytesWithBufferOf n h m = fromChunks h $ S.arraysOf n m
364-- fromBytesWithBufferOf n h m = fromChunks h $ AS.arraysOf n m
366-- > write = 'writeWithBufferOf' A.defaultChunkSize
367--
368-- | Write a byte stream to a file handle. Accumulates the input in chunks of
369-- up to 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing.
370--
371-- NOTE: This may perform better than the 'write' fold, you can try this if you
372-- need some extra perf boost.
373--
374-- @since 0.7.0
375{-# INLINE fromBytes #-}
376fromBytes :: MonadIO m => Handle -> SerialT m Word8 -> m ()
377fromBytes = fromBytesWithBufferOf defaultChunkSize
379-- | Write a stream of arrays to a handle. Each array in the stream is written
380-- to the device as a separate IO request.
381--
382-- @since 0.7.0
383{-# INLINE writeChunks #-}
384writeChunks :: (MonadIO m, Storable a) => Handle -> Fold m (Array a) ()
385writeChunks h = FL.drainBy (liftIO . writeArray h)
387-- | @writeChunksWithBufferOf bufsize handle@ writes a stream of arrays
388-- to @handle@ after coalescing the adjacent arrays in chunks of @bufsize@.
389-- We never split an array, if a single array is bigger than the specified size
390-- it emitted as it is. Multiple arrays are coalesed as long as the total size
391-- remains below the specified size.
392--
393-- @since 0.7.0
394{-# INLINE writeChunksWithBufferOf #-}
395writeChunksWithBufferOf :: (MonadIO m, Storable a)
396 => Int -> Handle -> Fold m (Array a) ()
397writeChunksWithBufferOf n h = lpackArraysChunksOf n (writeChunks h)
399-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
400--
401-- XXX test this
402-- Note that if you use a chunk size less than 8K (GHC's default buffer
403-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
404-- do not want buffering to occur at GHC level as well. Same thing applies to
405-- writes as well.
407-- | @writeWithBufferOf reqSize handle@ writes the input stream to @handle@.
408-- Bytes in the input stream are collected into a buffer until we have a chunk
409-- of @reqSize@ and then written to the IO device.
410--
411-- @since 0.7.0
412{-# INLINE writeWithBufferOf #-}
413writeWithBufferOf :: MonadIO m => Int -> Handle -> Fold m Word8 ()
414writeWithBufferOf n h = FL.lchunksOf n (writeNUnsafe n) (writeChunks h)
416-- > write = 'writeWithBufferOf' A.defaultChunkSize
417--
418-- | Write a byte stream to a file handle. Accumulates the input in chunks of
419-- up to 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before writing
420-- to the IO device.
421--
422-- @since 0.7.0
423{-# INLINE write #-}
424write :: MonadIO m => Handle -> Fold m Word8 ()
425write = writeWithBufferOf defaultChunkSize
427{-
428{-# INLINE write #-}
429write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
430write = toHandleWith A.defaultChunkSize
431-}
433-- XXX mmap a file into an array. This could be useful for in-place operations
434-- on a file. For example, we can quicksort the contents of a file by mmapping
435-- it.
437-------------------------------------------------------------------------------
438-- IO with encoding/decoding Unicode characters
439-------------------------------------------------------------------------------
441{-
442-- |
443-- > readUtf8 = decodeUtf8 . read
444--
445-- Read a UTF8 encoded stream of unicode characters from a file handle.
446--
447-- @since 0.7.0
448{-# INLINE readUtf8 #-}
449readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
450readUtf8 = decodeUtf8 . read
452-- |
453-- > writeUtf8 h s = write h $ encodeUtf8 s
454--
455-- Encode a stream of unicode characters to UTF8 and write it to the given file
456-- handle. Default block buffering applies to the writes.
457--
458-- @since 0.7.0
459{-# INLINE writeUtf8 #-}
460writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
461writeUtf8 h s = write h $ encodeUtf8 s
463-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
464-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
465-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
466-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
467-- option.
468--
469-- @since 0.7.0
470{-# INLINE writeUtf8ByLines #-}
471writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
472writeUtf8ByLines = undefined
474-- | Read UTF-8 lines from a file handle and apply the specified fold to each
475-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
476--
477-- @since 0.7.0
478{-# INLINE readLines #-}
479readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
480readLines h f = foldLines (readUtf8 h) f
482-------------------------------------------------------------------------------
483-- Framing on a sequence
484-------------------------------------------------------------------------------
486-- | Read a stream from a file handle and split it into frames delimited by
487-- the specified sequence of elements. The supplied fold is applied on each
488-- frame.
489--
490-- @since 0.7.0
491{-# INLINE readFrames #-}
492readFrames :: (IsStream t, MonadIO m, Storable a)
493 => Array a -> Handle -> Fold m a b -> t m b
494readFrames = undefined -- foldFrames . read
496-- | Write a stream to the given file handle buffering up to frames separated
497-- by the given sequence or up to a maximum of @defaultChunkSize@.
498--
499-- @since 0.7.0
500{-# INLINE writeByFrames #-}
501writeByFrames :: (IsStream t, MonadIO m, Storable a)
502 => Array a -> Handle -> t m a -> m ()
503writeByFrames = undefined
505-------------------------------------------------------------------------------
506-- Framing by time
507-------------------------------------------------------------------------------
509-- | Write collecting the input in sessions of n seconds or if chunkSize
510-- gets exceeded.
511{-# INLINE writeByChunksOrSessionsOf #-}
512writeByChunksOrSessionsOf :: MonadIO m
513 => Int -> Double -> Handle -> SerialT m Word8 -> m ()
514writeByChunksOrSessionsOf chunkSize sessionSize h m = undefined
516-- | Write collecting the input in sessions of n seconds or if defaultChunkSize
517-- gets exceeded.
518{-# INLINE writeBySessionsOf #-}
519writeBySessionsOf :: MonadIO m => Double -> Handle -> SerialT m Word8 -> m ()
520writeBySessionsOf n = writeByChunksOrSessionsOf defaultChunkSize n
522-------------------------------------------------------------------------------
523-- Random Access IO (Seek)
524-------------------------------------------------------------------------------
526-- XXX handles could be shared, so we may not want to use the handle state at
527-- all for these APIs. we can use pread and pwrite instead. On windows we will
528-- need to use readFile/writeFile with an offset argument.
530-------------------------------------------------------------------------------
532-- | Read the element at the given index treating the file as an array.
533--
534-- @since 0.7.0
535{-# INLINE readIndex #-}
536readIndex :: Storable a => Handle -> Int -> Maybe a
537readIndex arr i = undefined
539-- NOTE: To represent a range to read we have chosen (start, size) instead of
540-- (start, end). This helps in removing the ambiguity of whether "end" is
541-- included in the range or not.
542--
543-- We could avoid specifying the range to be read and instead use "take size"
544-- on the stream, but it may end up reading more and then consume it partially.
546-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
547-- from @handle@ starting at the offset @pos@ from the beginning of the file.
548--
549-- Reads are performed in chunks of size @chunkSize@. For block devices, to
550-- avoid reading partial blocks @chunkSize@ must align with the block size of
551-- the underlying device. If the underlying block size is unknown, it is a good
552-- idea to keep it a multiple 4KiB. This API ensures that the start of each
553-- chunk is aligned with @chunkSize@ from second chunk onwards.
554--
555{-# INLINE readSliceWith #-}
556readSliceWith :: (IsStream t, MonadIO m, Storable a)
557 => Int -> Handle -> Int -> Int -> t m a
558readSliceWith chunkSize h pos len = undefined
560-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
561-- at index @i@ and reading up to @count@ elements in the forward direction
562-- ending at the index @i + count - 1@.
563--
564-- @since 0.7.0
565{-# INLINE readSlice #-}
566readSlice :: (IsStream t, MonadIO m, Storable a)
567 => Handle -> Int -> Int -> t m a
568readSlice = readSliceWith A.defaultChunkSize
570-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
571-- at index @i@ and reading up to @count@ elements in the reverse direction
572-- ending at the index @i - count + 1@.
573--
574-- @since 0.7.0
575{-# INLINE readSliceRev #-}
576readSliceRev :: (IsStream t, MonadIO m, Storable a)
577 => Handle -> Int -> Int -> t m a
578readSliceRev h i count = undefined
580-- | Write the given element at the given index in the file.
581--
582-- @since 0.7.0
583{-# INLINE writeIndex #-}
584writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
585writeIndex h i a = undefined
587-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
588-- starting at index @i@ and writing up to @count@ elements in the forward
589-- direction ending at the index @i + count - 1@.
590--
591-- @since 0.7.0
592{-# INLINE writeSlice #-}
593writeSlice :: (IsStream t, Monad m, Storable a)
594 => Handle -> Int -> Int -> t m a -> m ()
595writeSlice h i len s = undefined
597-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
598-- starting at index @i@ and writing up to @count@ elements in the reverse
599-- direction ending at the index @i - count + 1@.
600--
601-- @since 0.7.0
602{-# INLINE writeSliceRev #-}
603writeSliceRev :: (IsStream t, Monad m, Storable a)
604 => Handle -> Int -> Int -> t m a -> m ()
605writeSliceRev arr i len s = undefined
606-}