2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
10-- Module : Streamly.FileSystem.Handle
11-- Copyright : (c) 2018 Harendra Kumar
14-- Maintainer : harendra.kumar@gmail.com
15-- Stability : experimental
18-- Read and write streams and arrays to and from file handles. File handle IO
19-- APIs are quite similar to "Streamly.Mem.Array" read write APIs. In that
20-- regard, arrays can be considered as in-memory files or files can be
21-- considered as on-disk arrays. IO APIs are divided into two categories,
22-- sequential streaming IO APIs and random access IO APIs. Control over the
23-- file reading and writing behavior in terms of buffering, encoding, decoding
24-- is in the hands of the programmer, the 'TextEncoding', 'NewLineMode', and
25-- 'Buffering' options of the underlying handle provided by GHC are not needed
28-- > import qualified Streamly.FileSystem.Handle as FH
31module Streamly.FileSystem.Handle
34 -- | Stream data to or from a file or device sequentially. When reading,
35 -- the stream is lazy and generated on-demand as the consumer consumes it.
36 -- Read IO requests to the IO device are performed in chunks limited to a
37 -- maximum size of 32KiB, this is referred to as @defaultChunkSize@ in the
38 -- documentation. One IO request may or may not read the full
39 -- chunk. If the whole stream is not consumed, it is possible that we may
40 -- read slightly more from the IO device than what the consumer needed.
41 -- Unless specified otherwise in the API, writes are collected into chunks
42 -- of @defaultChunkSize@ before they are written to the IO device.
44 -- Streaming APIs work for all kind of devices, seekable or non-seekable;
45 -- including disks, files, memory devices, terminals, pipes, sockets and
46 -- fifos. While random access APIs work only for files or devices that have
47 -- random access or seek capability for example disks, memory devices.
48 -- Devices like terminals, pipes, sockets and fifos do not have random
51 -- ** Read Handle to Stream
66 -- ** Write File from Stream
77 -- -- * Random Access (Seek)
78 -- -- | Unlike the streaming APIs listed above, these APIs apply to devices or
79 -- files that have random access or seek capability. This type of devices
80 -- include disks, files, memory devices and exclude terminals, pipes,
86 -- , readAt -- read from a given position to th end of file
87 -- , readSliceArrayUpto
93 -- , writeAt -- start writing at the given position
98import Control.Monad.IO.Class (MonadIO(..))
99import Data.Word (Word8)
100import Foreign.ForeignPtr (withForeignPtr)
101import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
102import Foreign.Ptr (minusPtr, plusPtr)
103import Foreign.Storable (Storable(..))
104import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
105import System.IO (Handle, hGetBufSome, hPutBuf)
106import Prelude hiding (read)
108import Streamly.Mem.Array.Types (Array(..))
109import Streamly.Streams.Serial (SerialT)
110import Streamly.Streams.StreamK.Type (IsStream, mkStream)
111-- import Streamly.Fold (Fold)
112-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
114import qualified Streamly.Mem.Array as A
115import qualified Streamly.Mem.Array.Types as A hiding (flattenArrays)
116import qualified Streamly.Prelude as S
118-------------------------------------------------------------------------------
120-------------------------------------------------------------------------------
122-- The following references may be useful to build an understanding about the
125-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
126-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
127-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
128-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
129-- https://www.w3.org/TR/FileAPI/ for http file API.
131-------------------------------------------------------------------------------
133-------------------------------------------------------------------------------
135-- | Read a 'ByteArray' from a file handle. If no data is available on the
136-- handle it blocks until some data becomes available. If data is available
137-- then it immediately returns that data without blocking. It reads a maximum
138-- of up to the size requested.
139{-# INLINABLE readArrayUpto #-}
140readArrayUpto :: Int -> Handle -> IO (Array Word8)
141readArrayUpto size h = do
142 ptr <- mallocPlainForeignPtrBytes size
143 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
144 withForeignPtr ptr $ \p -> do
145 n <- hGetBufSome h p size
148 , aEnd = p `plusPtr` n
149 , aBound = p `plusPtr` size
151 -- XXX shrink only if the diff is significant
154-------------------------------------------------------------------------------
156-------------------------------------------------------------------------------
158-- | Write an Array to a file handle.
161{-# INLINABLE writeArray #-}
162writeArray :: Storable a => Handle -> Array a -> IO ()
163writeArray _ arr | A.length arr == 0 = return ()
164writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
167 let p = unsafeForeignPtrToPtr aStart
170-------------------------------------------------------------------------------
171-- Stream of Arrays IO
172-------------------------------------------------------------------------------
174-- | @readArraysUpto size h@ reads a stream of arrays from file handle @h@.
175-- The maximum size of a single array is specified by @size@. The actual size
176-- read may be less than or equal to @size@.
177{-# INLINABLE readArraysUpto #-}
178readArraysUpto :: (IsStream t, MonadIO m)
179 => Int -> Handle -> t m (Array Word8)
180readArraysUpto size h = go
182 -- XXX use cons/nil instead
183 go = mkStream $ \_ yld _ stp -> do
184 arr <- liftIO $ readArrayUpto size h
189-- XXX read 'Array a' instead of Word8
191-- | @readArrays h@ reads a stream of arrays from file handle @h@.
192-- The maximum size of a single array is limited to @defaultChunkSize@.
193-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
196-- > readArrays = readArraysUpto defaultChunkSize
199{-# INLINE readArrays #-}
200readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
201readArrays = readArraysUpto A.defaultChunkSize
203-------------------------------------------------------------------------------
204-- Read File to Stream
205-------------------------------------------------------------------------------
207-- TODO for concurrent streams implement readahead IO. We can send multiple
208-- read requests at the same time. For serial case we can use async IO. We can
209-- also control the read throughput in mbps or IOPS.
212-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file
213-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
214-- as soon as EOF is encountered.
216{-# INLINE readByChunksUpto #-}
217readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
218readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
222-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
224-- > read = 'readByChunks' A.defaultChunkSize
225-- | Generate a stream of elements of the given type from a file 'Handle'. The
226-- stream ends when EOF is encountered.
230read :: (IsStream t, MonadIO m) => Handle -> t m Word8
231read = A.flattenArrays . readArrays
233-------------------------------------------------------------------------------
235-------------------------------------------------------------------------------
237-- | Write a stream of arrays to a handle.
240{-# INLINE writeArrays #-}
241writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
242writeArrays h m = S.mapM_ (liftIO . writeArray h) m
244-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
247-- Note that if you use a chunk size less than 8K (GHC's default buffer
248-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
249-- do not want buffering to occur at GHC level as well. Same thing applies to
252-- | Like 'write' but provides control over the write buffer. Output will
253-- be written to the IO device as soon as we collect the specified number of
257{-# INLINE writeByChunks #-}
258writeByChunks :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
259writeByChunks n h m = writeArrays h $ A.arraysOf n m
261-- > write = 'writeByChunks' A.defaultChunkSize
263-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
264-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
265-- depends on the 'IOMode' and the current seek position of the handle.
269write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
270write = writeByChunks A.defaultChunkSize
274write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
275write = toHandleWith A.defaultChunkSize
278-- XXX mmap a file into an array. This could be useful for in-place operations
279-- on a file. For example, we can quicksort the contents of a file by mmapping
282-------------------------------------------------------------------------------
283-- IO with encoding/decoding Unicode characters
284-------------------------------------------------------------------------------
288-- > readUtf8 = decodeUtf8 . read
290-- Read a UTF8 encoded stream of unicode characters from a file handle.
293{-# INLINE readUtf8 #-}
294readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
295readUtf8 = decodeUtf8 . read
298-- > writeUtf8 h s = write h $ encodeUtf8 s
300-- Encode a stream of unicode characters to UTF8 and write it to the given file
301-- handle. Default block buffering applies to the writes.
304{-# INLINE writeUtf8 #-}
305writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
306writeUtf8 h s = write h $ encodeUtf8 s
308-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
309-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
310-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
311-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
315{-# INLINE writeUtf8ByLines #-}
316writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
317writeUtf8ByLines = undefined
319-- | Read UTF-8 lines from a file handle and apply the specified fold to each
320-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
323{-# INLINE readLines #-}
324readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
325readLines h f = foldLines (readUtf8 h) f
327-------------------------------------------------------------------------------
328-- Framing on a sequence
329-------------------------------------------------------------------------------
331-- | Read a stream from a file handle and split it into frames delimited by
332-- the specified sequence of elements. The supplied fold is applied on each
336{-# INLINE readFrames #-}
337readFrames :: (IsStream t, MonadIO m, Storable a)
338 => Array a -> Handle -> Fold m a b -> t m b
339readFrames = undefined -- foldFrames . read
341-- | Write a stream to the given file handle buffering up to frames separated
342-- by the given sequence or up to a maximum of @defaultChunkSize@.
345{-# INLINE writeByFrames #-}
346writeByFrames :: (IsStream t, MonadIO m, Storable a)
347 => Array a -> Handle -> t m a -> m ()
348writeByFrames = undefined
350-------------------------------------------------------------------------------
351-- Random Access IO (Seek)
352-------------------------------------------------------------------------------
354-- XXX handles could be shared, so we may not want to use the handle state at
355-- all for these APIs. we can use pread and pwrite instead. On windows we will
356-- need to use readFile/writeFile with an offset argument.
358-------------------------------------------------------------------------------
360-- | Read the element at the given index treating the file as an array.
363{-# INLINE readIndex #-}
364readIndex :: Storable a => Handle -> Int -> Maybe a
365readIndex arr i = undefined
367-- NOTE: To represent a range to read we have chosen (start, size) instead of
368-- (start, end). This helps in removing the ambiguity of whether "end" is
369-- included in the range or not.
371-- We could avoid specifying the range to be read and instead use "take size"
372-- on the stream, but it may end up reading more and then consume it partially.
374-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
375-- from @handle@ starting at the offset @pos@ from the beginning of the file.
377-- Reads are performed in chunks of size @chunkSize@. For block devices, to
378-- avoid reading partial blocks @chunkSize@ must align with the block size of
379-- the underlying device. If the underlying block size is unknown, it is a good
380-- idea to keep it a multiple 4KiB. This API ensures that the start of each
381-- chunk is aligned with @chunkSize@ from second chunk onwards.
383{-# INLINE readSliceWith #-}
384readSliceWith :: (IsStream t, MonadIO m, Storable a)
385 => Int -> Handle -> Int -> Int -> t m a
386readSliceWith chunkSize h pos len = undefined
388-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
389-- at index @i@ and reading up to @count@ elements in the forward direction
390-- ending at the index @i + count - 1@.
393{-# INLINE readSlice #-}
394readSlice :: (IsStream t, MonadIO m, Storable a)
395 => Handle -> Int -> Int -> t m a
396readSlice = readSliceWith A.defaultChunkSize
398-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
399-- at index @i@ and reading up to @count@ elements in the reverse direction
400-- ending at the index @i - count + 1@.
403{-# INLINE readSliceRev #-}
404readSliceRev :: (IsStream t, MonadIO m, Storable a)
405 => Handle -> Int -> Int -> t m a
406readSliceRev h i count = undefined
408-- | Write the given element at the given index in the file.
411{-# INLINE writeIndex #-}
412writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
413writeIndex h i a = undefined
415-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
416-- starting at index @i@ and writing up to @count@ elements in the forward
417-- direction ending at the index @i + count - 1@.
420{-# INLINE writeSlice #-}
421writeSlice :: (IsStream t, Monad m, Storable a)
422 => Handle -> Int -> Int -> t m a -> m ()
423writeSlice h i len s = undefined
425-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
426-- starting at index @i@ and writing up to @count@ elements in the reverse
427-- direction ending at the index @i - count + 1@.
430{-# INLINE writeSliceRev #-}
431writeSliceRev :: (IsStream t, Monad m, Storable a)
432 => Handle -> Int -> Int -> t m a -> m ()
433writeSliceRev 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