on 80daa14 help sign in
499 lines 17 kB history raw
1{-# LANGUAGE UnboxedTuples #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Internal.Memory.Array
7-- Copyright : (c) 2019 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
14-- To summarize:
15--
16-- * Arrays are finite and fixed in size
17-- * provide /O(1)/ access to elements
18-- * store only data and not functions
19-- * provide efficient IO interfacing
20--
21-- 'Foldable' instance is not provided because the implementation would be much
22-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
23-- instances should be used with care; concatenating arrays using binary
24-- operations can be highly inefficient. Instead, use
25-- 'Streamly.Internal.Memory.ArrayStream.toArray' to concatenate N arrays at
26-- once.
27--
28-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
29-- single byte) are only as good as holding those elements in a Haskell list.
30-- However, small arrays can be compacted into large ones to reduce the
31-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
32-- if we use one array for each chunk. This is still significant to add
33-- pressure to GC.
35module Streamly.Internal.Memory.Array
36 (
37 Array
39 -- , defaultChunkSize
41 -- * Construction
43 -- Pure List APIs
44 , A.fromListN
45 , A.fromList
47 -- Stream Folds
48 , fromStreamN
49 , fromStream
51 -- Monadic APIs
52 -- , newArray
53 , A.writeN -- drop new
54 , A.writeNAligned
55 , A.write -- full buffer
56 -- , writeLastN -- drop old (ring buffer)
58 -- * Elimination
60 , A.toList
61 , toStream
62 , toStreamRev
63 , read
64 , ReadUState (..)
65 , unsafeRead
66 -- , readChunksOf
68 -- * Random Access
69 , length
70 , null
71 , last
72 -- , (!!)
73 , readIndex
74 , A.unsafeIndex
75 -- , readIndices
76 -- , readRanges
78 -- , readFrom -- read from a given position to the end of file
79 -- , readFromRev -- read from a given position to the beginning of file
80 -- , readTo -- read from beginning up to the given position
81 -- , readToRev -- read from end to the given position in file
82 -- , readFromTo
83 -- , readFromThenTo
85 -- , readChunksOfFrom
86 -- , ...
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 -- , writeChunksOfFrom
97 -- , ...
99 , writeIndex
100 --, writeIndices
101 --, writeRanges
103 -- -- * Search
104 -- , bsearch
105 -- , bsearchIndex
106 -- , find
107 -- , findIndex
108 -- , findIndices
110 -- -- * In-pace mutation (for Mutable Array type)
111 -- , partitionBy
112 -- , shuffleBy
113 -- , foldtWith
114 -- , foldbWith
116 -- * Immutable Transformations
117 , streamTransform
119 -- * Folding Arrays
120 , streamFold
121 , fold
123 -- * Folds with Array as the container
124 , D.lastN
125 )
126where
128import Control.Monad (when)
129import Control.Monad.IO.Class (MonadIO(..))
130-- import Data.Functor.Identity (Identity)
131import Foreign.ForeignPtr (withForeignPtr, touchForeignPtr)
132import Foreign.Ptr (plusPtr)
133import Foreign.Storable (Storable(..))
134import Prelude hiding (length, null, last, map, (!!), read, concat)
136import GHC.ForeignPtr (ForeignPtr(..))
137import GHC.Ptr (Ptr(..))
138import GHC.Prim (touch#)
139import GHC.IO (IO(..))
141import Streamly.Internal.Data.Fold.Types (Fold(..))
142import Streamly.Internal.Data.Unfold.Types (Unfold(..))
143import Streamly.Internal.Memory.Array.Types (Array(..), length)
144import Streamly.Internal.Data.Stream.Serial (SerialT)
145import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
147import qualified Streamly.Internal.Memory.Array.Types as A
148import qualified Streamly.Internal.Data.Stream.Prelude as P
149import qualified Streamly.Internal.Data.Stream.Serial as Serial
150import qualified Streamly.Internal.Data.Stream.StreamD as D
151import qualified Streamly.Internal.Data.Stream.StreamK as K
153-------------------------------------------------------------------------------
154-- Construction
155-------------------------------------------------------------------------------
157-- | Create an 'Array' from the first N elements of a stream. The array is
158-- allocated to size N, if the stream terminates before N elements then the
159-- array may hold less than N elements.
160--
161-- /Internal/
162{-# INLINE fromStreamN #-}
163fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
164fromStreamN n m = do
165 when (n < 0) $ error "writeN: negative write count specified"
166 A.fromStreamDN n $ D.toStreamD m
168-- | Create an 'Array' from a stream. This is useful when we want to create a
169-- single array from a stream of unknown size. 'writeN' is at least twice
170-- as efficient when the size is already known.
171--
172-- Note that if the input stream is too large memory allocation for the array
173-- may fail. When the stream size is not known, `arraysOf` followed by
174-- processing of indvidual arrays in the resulting stream should be preferred.
175--
176-- /Internal/
177{-# INLINE fromStream #-}
178fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
179fromStream = P.runFold A.write
180-- write m = A.fromStreamD $ D.toStreamD m
182-------------------------------------------------------------------------------
183-- Elimination
184-------------------------------------------------------------------------------
186-- | Convert an 'Array' into a stream.
187--
188-- /Internal/
189{-# INLINE_EARLY toStream #-}
190toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
191toStream = D.fromStreamD . A.toStreamD
192-- XXX add fallback to StreamK rule
193-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
194-- forall a. S.readK (read a) = K.fromArray a #-}
196-- | Convert an 'Array' into a stream in reverse order.
197--
198-- /Internal/
199{-# INLINE_EARLY toStreamRev #-}
200toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
201toStreamRev = D.fromStreamD . A.toStreamDRev
202-- XXX add fallback to StreamK rule
203-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
204-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
206data ReadUState a = ReadUState
207 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
208 {-# UNPACK #-} !(Ptr a) -- current pointer
210-- | Unfold an array into a stream.
211--
212-- @since 0.7.0
213{-# INLINE_NORMAL read #-}
214read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
215read = Unfold step inject
216 where
218 inject (Array (ForeignPtr start contents) (Ptr end)) =
219 return $ ReadUState (ForeignPtr end contents) (Ptr start)
221 {-# INLINE_LATE step #-}
222 step (ReadUState fp@(ForeignPtr end _) p) | p == Ptr end =
223 let x = A.unsafeInlineIO $ touchForeignPtr fp
224 in x `seq` return D.Stop
225 step (ReadUState fp p) = do
226 -- unsafeInlineIO allows us to run this in Identity monad for pure
227 -- toList/foldr case which makes them much faster due to not
228 -- accumulating the list and fusing better with the pure consumers.
229 --
230 -- This should be safe as the array contents are guaranteed to be
231 -- evaluated/written to before we peek at them.
232 let !x = A.unsafeInlineIO $ peek p
233 return $ D.Yield x
234 (ReadUState fp (p `plusPtr` sizeOf (undefined :: a)))
236-- | Unfold an array into a stream, does not check the end of the array, the
237-- user is responsible for terminating the stream within the array bounds. For
238-- high performance application where the end condition can be determined by
239-- a terminating fold.
240--
241-- Written in the hope that it may be faster than "read", however, in the case
242-- for which this was written, "read" proves to be faster even though the core
243-- generated with unsafeRead looks simpler.
244--
245-- /Internal/
246--
247{-# INLINE_NORMAL unsafeRead #-}
248unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
249unsafeRead = Unfold step inject
250 where
252 inject (Array fp _) = return fp
254 {-# INLINE_LATE step #-}
255 step (ForeignPtr p contents) = do
256 -- unsafeInlineIO allows us to run this in Identity monad for pure
257 -- toList/foldr case which makes them much faster due to not
258 -- accumulating the list and fusing better with the pure consumers.
259 --
260 -- This should be safe as the array contents are guaranteed to be
261 -- evaluated/written to before we peek at them.
262 let !x = A.unsafeInlineIO $ do
263 r <- peek (Ptr p)
264 touch contents
265 return r
266 let !(Ptr p1) = Ptr p `plusPtr` sizeOf (undefined :: a)
267 return $ D.Yield x (ForeignPtr p1 contents)
269 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
271-- | > null arr = length arr == 0
272--
273-- /Internal/
274{-# INLINE null #-}
275null :: Storable a => Array a -> Bool
276null arr = length arr == 0
278-- | > last arr = readIndex arr (length arr - 1)
279--
280-- /Internal/
281{-# INLINE last #-}
282last :: Storable a => Array a -> Maybe a
283last arr = readIndex arr (length arr - 1)
285-------------------------------------------------------------------------------
286-- Random Access
287-------------------------------------------------------------------------------
289-------------------------------------------------------------------------------
290-- Searching
291-------------------------------------------------------------------------------
293{-
294-- | Perform a binary search in the array to find an element.
295bsearch :: a -> Array a -> Maybe Bool
296bsearch = undefined
298-- | Perform a binary search in the array to find an element index.
299{-# INLINE elemIndex #-}
300bsearchIndex :: a -> Array a -> Maybe Int
301bsearchIndex elem arr = undefined
303-- find/findIndex etc can potentially be implemented more efficiently on arrays
304-- compared to streams by using SIMD instructions.
306find :: (a -> Bool) -> Array a -> Bool
307find = undefined
309findIndex :: (a -> Bool) -> Array a -> Maybe Int
310findIndex = undefined
312findIndices :: (a -> Bool) -> Array a -> Array Int
313findIndices = undefined
314-}
316-------------------------------------------------------------------------------
317-- Folds
318-------------------------------------------------------------------------------
320-- XXX We can potentially use SIMD instructions on arrays to fold faster.
322-------------------------------------------------------------------------------
323-- Slice and splice
324-------------------------------------------------------------------------------
326{-
327slice :: Int -> Int -> Array a
328slice begin end arr = undefined
330splitAt :: Int -> Array a -> (Array a, Array a)
331splitAt i arr = undefined
333-- XXX This operation can be performed efficiently via streams.
334-- | Append two arrays together to create a single array.
335splice :: Array a -> Array a -> Array a
336splice arr1 arr2 = undefined
338-------------------------------------------------------------------------------
339-- In-place mutation APIs
340-------------------------------------------------------------------------------
342-- | Partition an array into two halves using a partitioning predicate. The
343-- first half retains values where the predicate is 'False' and the second half
344-- retains values where the predicate is 'True'.
345{-# INLINE partitionBy #-}
346partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
347partitionBy f arr = undefined
349-- | Shuffle corresponding elements from two arrays using a shuffle function.
350-- If the shuffle function returns 'False' then do nothing otherwise swap the
351-- elements. This can be used in a bottom up fold to shuffle or reorder the
352-- elements.
353shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
354shuffleBy f arr1 arr2 = undefined
356-- XXX we can also make the folds partial by stopping at a certain level.
357--
358-- | Perform a top down hierarchical recursive partitioning fold of items in
359-- the container using the given function as the partition function.
360--
361-- This will perform a quick sort if the partition function is
362-- 'partitionBy (< pivot)'.
363--
364-- @since 0.7.0
365{-# INLINABLE foldtWith #-}
366foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
367foldtWith level f = undefined
369-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
370-- indicates the level in the tree where the fold would stop.
371--
372-- This will perform a random shuffle if the shuffle function is random.
373-- If we stop at level 0 and repeatedly apply the function then we can do a
374-- bubble sort.
375foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
376foldbWith level f = undefined
377-}
379-- XXX consider the bulk update/accumulation/permutation APIs from vector.
381-------------------------------------------------------------------------------
382-- Random reads and writes
383-------------------------------------------------------------------------------
385-- | /O(1)/ Lookup the element at the given index, starting from 0.
386--
387-- /Internal/
388{-# INLINE readIndex #-}
389readIndex :: Storable a => Array a -> Int -> Maybe a
390readIndex arr i =
391 if i < 0 || i > length arr - 1
392 then Nothing
393 else A.unsafeInlineIO $
394 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
396{-
397-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
398-- at index @i@ and reading up to @count@ elements in the forward direction
399-- ending at the index @i + count - 1@.
400--
401-- @since 0.7.0
402{-# INLINE readSlice #-}
403readSlice :: (IsStream t, Monad m, Storable a)
404 => Array a -> Int -> Int -> t m a
405readSlice arr i len = undefined
407-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
408-- index @i@ and reading up to @count@ elements in the reverse direction ending
409-- at the index @i - count + 1@.
410--
411-- @since 0.7.0
412{-# INLINE readSliceRev #-}
413readSliceRev :: (IsStream t, Monad m, Storable a)
414 => Array a -> Int -> Int -> t m a
415readSliceRev arr i len = undefined
416-}
418-- | /O(1)/ Write the given element at the given index in the array.
419-- Performs in-place mutation of the array.
420--
421-- /Internal/
422{-# INLINE writeIndex #-}
423writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
424writeIndex arr i a = do
425 let maxIndex = length arr - 1
426 if i < 0
427 then error "writeIndex: negative array index"
428 else if i > maxIndex
429 then error $ "writeIndex: specified array index " ++ show i
430 ++ " is beyond the maximum index " ++ show maxIndex
431 else
432 liftIO $ withForeignPtr (aStart arr) $ \p ->
433 pokeElemOff p i a
435{-
436-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
437-- starting at index @i@ and writing up to @count@ elements in the forward
438-- direction ending at the index @i + count - 1@.
439--
440-- @since 0.7.0
441{-# INLINE writeSlice #-}
442writeSlice :: (IsStream t, Monad m, Storable a)
443 => Array a -> Int -> Int -> t m a -> m (Array a)
444writeSlice arr i len s = undefined
446-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
447-- starting at index @i@ and writing up to @count@ elements in the reverse
448-- direction ending at the index @i - count + 1@.
449--
450-- @since 0.7.0
451{-# INLINE writeSliceRev #-}
452writeSliceRev :: (IsStream t, Monad m, Storable a)
453 => Array a -> Int -> Int -> t m a -> m (Array a)
454writeSliceRev arr i len s = undefined
455-}
457-------------------------------------------------------------------------------
458-- Transform via stream operations
459-------------------------------------------------------------------------------
461-- for non-length changing operations we can use the original length for
462-- allocation. If we can predict the length then we can use the prediction for
463-- new allocation. Otherwise we can use a hint and adjust dynamically.
465{-
466-- | Transform an array into another array using a pipe transformation
467-- operation.
468--
469-- @since 0.7.0
470{-# INLINE runPipe #-}
471runPipe :: (MonadIO m, Storable a, Storable b)
472 => Pipe m a b -> Array a -> m (Array b)
473runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
474-}
476-- | Transform an array into another array using a stream transformation
477-- operation.
478--
479-- /Internal/
480{-# INLINE streamTransform #-}
481streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
482 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
483streamTransform f arr =
484 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
485 $ f (toStream arr)
487-- | Fold an array using a 'Fold'.
488--
489-- /Internal/
490{-# INLINE fold #-}
491fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
492fold f arr = P.runFold f (toStream arr :: Serial.SerialT m a)
494-- | Fold an array using a stream fold operation.
495--
496-- /Internal/
497{-# INLINE streamFold #-}
498streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
499streamFold f arr = f (toStream arr)