on 2255dac help sign in
447 lines 17 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.FileSystem.Handle
11-- Copyright : (c) 2018 Harendra Kumar
12--
13-- License : BSD3
14-- Maintainer : harendra.kumar@gmail.com
15-- Stability : experimental
16-- Portability : GHC
17--
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
26-- and ignored.
27--
28-- > import qualified Streamly.FileSystem.Handle as FH
29--
31module Streamly.FileSystem.Handle
32 (
33 -- * Streaming IO
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
49 -- access capability.
51 -- ** Read Handle to Stream
52 read
53 -- , readUtf8
54 -- , readLines
55 -- , readFrames
56 -- , readByChunks
58 -- -- * Array Read
59 -- , readArrayUpto
60 -- , readArrayOf
62 , readArraysUpto
63 -- , readArraysOf
64 , readArrays
66 -- ** Write File from Stream
67 , write
68 -- , writeUtf8
69 -- , writeUtf8ByLines
70 -- , writeByFrames
71 , writeByChunks
73 -- -- * Array Write
74 , writeArray
75 , writeArrays
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,
81 -- sockets and fifos.
82 --
83 -- , readIndex
84 -- , readSlice
85 -- , readSliceRev
86 -- , readAt -- read from a given position to th end of file
87 -- , readSliceArrayUpto
88 -- , readSliceArrayOf
90 -- , writeIndex
91 -- , writeSlice
92 -- , writeSliceRev
93 -- , writeAt -- start writing at the given position
94 -- , writeSliceArray
95 )
96where
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
117import qualified Streamly.Streams.StreamD.Type as D
119-------------------------------------------------------------------------------
120-- References
121-------------------------------------------------------------------------------
122--
123-- The following references may be useful to build an understanding about the
124-- file API design:
125--
126-- http://www.linux-mag.com/id/308/ for blocking/non-blocking IO on linux.
127-- https://lwn.net/Articles/612483/ Non-blocking buffered file read operations
128-- https://en.wikipedia.org/wiki/C_file_input/output for C APIs.
129-- https://docs.oracle.com/javase/tutorial/essential/io/file.html for Java API.
130-- https://www.w3.org/TR/FileAPI/ for http file API.
132-------------------------------------------------------------------------------
133-- Array IO (Input)
134-------------------------------------------------------------------------------
136-- | Read a 'ByteArray' from a file handle. If no data is available on the
137-- handle it blocks until some data becomes available. If data is available
138-- then it immediately returns that data without blocking. It reads a maximum
139-- of up to the size requested.
140{-# INLINABLE readArrayUpto #-}
141readArrayUpto :: Int -> Handle -> IO (Array Word8)
142readArrayUpto size h = do
143 ptr <- mallocPlainForeignPtrBytes size
144 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
145 withForeignPtr ptr $ \p -> do
146 n <- hGetBufSome h p size
147 let v = Array
148 { aStart = ptr
149 , aEnd = p `plusPtr` n
150 , aBound = p `plusPtr` size
151 }
152 -- XXX shrink only if the diff is significant
153 A.shrinkToFit v
155-------------------------------------------------------------------------------
156-- Array IO (output)
157-------------------------------------------------------------------------------
159-- | Write an Array to a file handle.
160--
161-- @since 0.7.0
162{-# INLINABLE writeArray #-}
163writeArray :: Storable a => Handle -> Array a -> IO ()
164writeArray _ arr | A.length arr == 0 = return ()
165writeArray h Array{..} = withForeignPtr aStart $ \p -> hPutBuf h p aLen
166 where
167 aLen =
168 let p = unsafeForeignPtrToPtr aStart
169 in aEnd `minusPtr` p
171-------------------------------------------------------------------------------
172-- Stream of Arrays IO
173-------------------------------------------------------------------------------
175-- | @readArraysUpto size h@ reads a stream of arrays from file handle @h@.
176-- The maximum size of a single array is specified by @size@. The actual size
177-- read may be less than or equal to @size@.
178{-# INLINABLE _readArraysUpto #-}
179_readArraysUpto :: (IsStream t, MonadIO m)
180 => Int -> Handle -> t m (Array Word8)
181_readArraysUpto size h = go
182 where
183 -- XXX use cons/nil instead
184 go = mkStream $ \_ yld _ stp -> do
185 arr <- liftIO $ readArrayUpto size h
186 if A.length arr == 0
187 then stp
188 else yld arr go
190{-# INLINE_NORMAL readArraysUpto #-}
191readArraysUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m (Array Word8)
192readArraysUpto 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-- XXX read 'Array a' instead of Word8
203--
204-- | @readArrays h@ reads a stream of arrays from file handle @h@.
205-- The maximum size of a single array is limited to @defaultChunkSize@.
206-- 'readArrays' ignores the prevailing 'TextEncoding' and 'NewlineMode'
207-- on the 'Handle'.
208--
209-- > readArrays = readArraysUpto defaultChunkSize
210--
211-- @since 0.7.0
212{-# INLINE readArrays #-}
213readArrays :: (IsStream t, MonadIO m) => Handle -> t m (Array Word8)
214readArrays = readArraysUpto A.defaultChunkSize
216-------------------------------------------------------------------------------
217-- Read File to Stream
218-------------------------------------------------------------------------------
220-- TODO for concurrent streams implement readahead IO. We can send multiple
221-- read requests at the same time. For serial case we can use async IO. We can
222-- also control the read throughput in mbps or IOPS.
224{-
225-- | @readByChunksUpto chunkSize handle@ reads a byte stream from a file
226-- handle, reads are performed in chunks of up to @chunkSize@. The stream ends
227-- as soon as EOF is encountered.
228--
229{-# INLINE readByChunksUpto #-}
230readByChunksUpto :: (IsStream t, MonadIO m) => Int -> Handle -> t m Word8
231readByChunksUpto chunkSize h = A.flattenArrays $ readArraysUpto chunkSize h
232-}
234-- TODO
235-- read :: (IsStream t, MonadIO m, Storable a) => Handle -> t m a
236--
237-- > read = 'readByChunks' A.defaultChunkSize
238-- | Generate a stream of elements of the given type from a file 'Handle'. The
239-- stream ends when EOF is encountered.
240--
241-- @since 0.7.0
242{-# INLINE read #-}
243read :: (IsStream t, MonadIO m) => Handle -> t m Word8
244read = A.flattenArrays . readArrays
246-------------------------------------------------------------------------------
247-- Writing
248-------------------------------------------------------------------------------
250-- | Write a stream of arrays to a handle.
251--
252-- @since 0.7.0
253{-# INLINE writeArrays #-}
254writeArrays :: (MonadIO m, Storable a) => Handle -> SerialT m (Array a) -> m ()
255writeArrays h m = S.mapM_ (liftIO . writeArray h) m
257-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
258--
259-- XXX test this
260-- Note that if you use a chunk size less than 8K (GHC's default buffer
261-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
262-- do not want buffering to occur at GHC level as well. Same thing applies to
263-- writes as well.
265-- | Like 'write' but provides control over the write buffer. Output will
266-- be written to the IO device as soon as we collect the specified number of
267-- input elements.
268--
269-- @since 0.7.0
270{-# INLINE writeByChunks #-}
271writeByChunks :: MonadIO m => Int -> Handle -> SerialT m Word8 -> m ()
272writeByChunks n h m = writeArrays h $ A.arraysOf n m
274-- > write = 'writeByChunks' A.defaultChunkSize
275--
276-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
277-- up to 'A.defaultChunkSize' before writing. Note that the write behavior
278-- depends on the 'IOMode' and the current seek position of the handle.
279--
280-- @since 0.7.0
281{-# INLINE write #-}
282write :: MonadIO m => Handle -> SerialT m Word8 -> m ()
283write = writeByChunks A.defaultChunkSize
285{-
286{-# INLINE write #-}
287write :: (MonadIO m, Storable a) => Handle -> SerialT m a -> m ()
288write = toHandleWith A.defaultChunkSize
289-}
291-- XXX mmap a file into an array. This could be useful for in-place operations
292-- on a file. For example, we can quicksort the contents of a file by mmapping
293-- it.
295-------------------------------------------------------------------------------
296-- IO with encoding/decoding Unicode characters
297-------------------------------------------------------------------------------
299{-
300-- |
301-- > readUtf8 = decodeUtf8 . read
302--
303-- Read a UTF8 encoded stream of unicode characters from a file handle.
304--
305-- @since 0.7.0
306{-# INLINE readUtf8 #-}
307readUtf8 :: (IsStream t, MonadIO m) => Handle -> t m Char
308readUtf8 = decodeUtf8 . read
310-- |
311-- > writeUtf8 h s = write h $ encodeUtf8 s
312--
313-- Encode a stream of unicode characters to UTF8 and write it to the given file
314-- handle. Default block buffering applies to the writes.
315--
316-- @since 0.7.0
317{-# INLINE writeUtf8 #-}
318writeUtf8 :: MonadIO m => Handle -> SerialT m Char -> m ()
319writeUtf8 h s = write h $ encodeUtf8 s
321-- | Write a stream of unicode characters after encoding to UTF-8 in chunks
322-- separated by a linefeed character @'\n'@. If the size of the buffer exceeds
323-- @defaultChunkSize@ and a linefeed is not yet found, the buffer is written
324-- anyway. This is similar to writing to a 'Handle' with the 'LineBuffering'
325-- option.
326--
327-- @since 0.7.0
328{-# INLINE writeUtf8ByLines #-}
329writeUtf8ByLines :: (IsStream t, MonadIO m) => Handle -> t m Char -> m ()
330writeUtf8ByLines = undefined
332-- | Read UTF-8 lines from a file handle and apply the specified fold to each
333-- line. This is similar to reading a 'Handle' with the 'LineBuffering' option.
334--
335-- @since 0.7.0
336{-# INLINE readLines #-}
337readLines :: (IsStream t, MonadIO m) => Handle -> Fold m Char b -> t m b
338readLines h f = foldLines (readUtf8 h) f
340-------------------------------------------------------------------------------
341-- Framing on a sequence
342-------------------------------------------------------------------------------
344-- | Read a stream from a file handle and split it into frames delimited by
345-- the specified sequence of elements. The supplied fold is applied on each
346-- frame.
347--
348-- @since 0.7.0
349{-# INLINE readFrames #-}
350readFrames :: (IsStream t, MonadIO m, Storable a)
351 => Array a -> Handle -> Fold m a b -> t m b
352readFrames = undefined -- foldFrames . read
354-- | Write a stream to the given file handle buffering up to frames separated
355-- by the given sequence or up to a maximum of @defaultChunkSize@.
356--
357-- @since 0.7.0
358{-# INLINE writeByFrames #-}
359writeByFrames :: (IsStream t, MonadIO m, Storable a)
360 => Array a -> Handle -> t m a -> m ()
361writeByFrames = undefined
363-------------------------------------------------------------------------------
364-- Random Access IO (Seek)
365-------------------------------------------------------------------------------
367-- XXX handles could be shared, so we may not want to use the handle state at
368-- all for these APIs. we can use pread and pwrite instead. On windows we will
369-- need to use readFile/writeFile with an offset argument.
371-------------------------------------------------------------------------------
373-- | Read the element at the given index treating the file as an array.
374--
375-- @since 0.7.0
376{-# INLINE readIndex #-}
377readIndex :: Storable a => Handle -> Int -> Maybe a
378readIndex arr i = undefined
380-- NOTE: To represent a range to read we have chosen (start, size) instead of
381-- (start, end). This helps in removing the ambiguity of whether "end" is
382-- included in the range or not.
383--
384-- We could avoid specifying the range to be read and instead use "take size"
385-- on the stream, but it may end up reading more and then consume it partially.
387-- | @readSliceWith chunkSize handle pos len@ reads up to @len@ bytes
388-- from @handle@ starting at the offset @pos@ from the beginning of the file.
389--
390-- Reads are performed in chunks of size @chunkSize@. For block devices, to
391-- avoid reading partial blocks @chunkSize@ must align with the block size of
392-- the underlying device. If the underlying block size is unknown, it is a good
393-- idea to keep it a multiple 4KiB. This API ensures that the start of each
394-- chunk is aligned with @chunkSize@ from second chunk onwards.
395--
396{-# INLINE readSliceWith #-}
397readSliceWith :: (IsStream t, MonadIO m, Storable a)
398 => Int -> Handle -> Int -> Int -> t m a
399readSliceWith chunkSize h pos len = undefined
401-- | @readSlice h i count@ streams a slice from the file handle @h@ starting
402-- at index @i@ and reading up to @count@ elements in the forward direction
403-- ending at the index @i + count - 1@.
404--
405-- @since 0.7.0
406{-# INLINE readSlice #-}
407readSlice :: (IsStream t, MonadIO m, Storable a)
408 => Handle -> Int -> Int -> t m a
409readSlice = readSliceWith A.defaultChunkSize
411-- | @readSliceRev h i count@ streams a slice from the file handle @h@ starting
412-- at index @i@ and reading up to @count@ elements in the reverse direction
413-- ending at the index @i - count + 1@.
414--
415-- @since 0.7.0
416{-# INLINE readSliceRev #-}
417readSliceRev :: (IsStream t, MonadIO m, Storable a)
418 => Handle -> Int -> Int -> t m a
419readSliceRev h i count = undefined
421-- | Write the given element at the given index in the file.
422--
423-- @since 0.7.0
424{-# INLINE writeIndex #-}
425writeIndex :: (MonadIO m, Storable a) => Handle -> Int -> a -> m ()
426writeIndex h i a = undefined
428-- | @writeSlice h i count stream@ writes a stream to the file handle @h@
429-- starting at index @i@ and writing up to @count@ elements in the forward
430-- direction ending at the index @i + count - 1@.
431--
432-- @since 0.7.0
433{-# INLINE writeSlice #-}
434writeSlice :: (IsStream t, Monad m, Storable a)
435 => Handle -> Int -> Int -> t m a -> m ()
436writeSlice h i len s = undefined
438-- | @writeSliceRev h i count stream@ writes a stream to the file handle @h@
439-- starting at index @i@ and writing up to @count@ elements in the reverse
440-- direction ending at the index @i - count + 1@.
441--
442-- @since 0.7.0
443{-# INLINE writeSliceRev #-}
444writeSliceRev :: (IsStream t, Monad m, Storable a)
445 => Handle -> Int -> Int -> t m a -> m ()
446writeSliceRev arr i len s = undefined
447-}