1{-# LANGUAGE UnboxedTuples #-}
6-- Module : Streamly.Internal.Memory.Array
7-- Copyright : (c) 2019 Composewell Technologies
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
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
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
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
35module Streamly.Internal.Memory.Array
53 , A.writeN -- drop new
55 , A.write -- full buffer
56 -- , writeLastN -- drop old (ring buffer)
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
89 -- , writeFrom -- start writing at the given position
91 -- , writeTo -- write from beginning up to the given position
96 -- , writeChunksOfFrom
110 -- -- * In-pace mutation (for Mutable Array type)
116 -- * Immutable Transformations
123 -- * Folds with Array as the container
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-------------------------------------------------------------------------------
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.
162{-# INLINE fromStreamN #-}
163fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
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.
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.
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-------------------------------------------------------------------------------
184-------------------------------------------------------------------------------
186-- | Convert an 'Array' into a stream.
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.
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.
213{-# INLINE_NORMAL read #-}
214read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
215read = Unfold step inject
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.
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
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.
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.
247{-# INLINE_NORMAL unsafeRead #-}
248unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
249unsafeRead = Unfold step inject
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.
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
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
275null :: Storable a => Array a -> Bool
276null arr = length arr == 0
278-- | > last arr = readIndex arr (length arr - 1)
282last :: Storable a => Array a -> Maybe a
283last arr = readIndex arr (length arr - 1)
285-------------------------------------------------------------------------------
287-------------------------------------------------------------------------------
289-------------------------------------------------------------------------------
291-------------------------------------------------------------------------------
294-- | Perform a binary search in the array to find an element.
295bsearch :: a -> Array a -> Maybe Bool
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
309findIndex :: (a -> Bool) -> Array a -> Maybe Int
312findIndices :: (a -> Bool) -> Array a -> Array Int
313findIndices = undefined
316-------------------------------------------------------------------------------
318-------------------------------------------------------------------------------
320-- XXX We can potentially use SIMD instructions on arrays to fold faster.
322-------------------------------------------------------------------------------
324-------------------------------------------------------------------------------
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
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.
358-- | Perform a top down hierarchical recursive partitioning fold of items in
359-- the container using the given function as the partition function.
361-- This will perform a quick sort if the partition function is
362-- 'partitionBy (< pivot)'.
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.
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
375foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
376foldbWith level f = undefined
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.
388{-# INLINE readIndex #-}
389readIndex :: Storable a => Array a -> Int -> Maybe a
391 if i < 0 || i > length arr - 1
393 else A.unsafeInlineIO $
394 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
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@.
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@.
412{-# INLINE readSliceRev #-}
413readSliceRev :: (IsStream t, Monad m, Storable a)
414 => Array a -> Int -> Int -> t m a
415readSliceRev arr i len = undefined
418-- | /O(1)/ Write the given element at the given index in the array.
419-- Performs in-place mutation of the array.
422{-# INLINE writeIndex #-}
423writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
424writeIndex arr i a = do
425 let maxIndex = length arr - 1
427 then error "writeIndex: negative array index"
429 then error $ "writeIndex: specified array index " ++ show i
430 ++ " is beyond the maximum index " ++ show maxIndex
432 liftIO $ withForeignPtr (aStart arr) $ \p ->
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@.
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@.
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
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.
466-- | Transform an array into another array using a pipe transformation
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)
476-- | Transform an array into another array using a stream transformation
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))
487-- | Fold an array using a '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.
497{-# INLINE streamFold #-}
498streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
499streamFold f arr = f (toStream arr)
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