1{-# OPTIONS_HADDOCK hide #-}
2{-# LANGUAGE BangPatterns #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
7{-# LANGUAGE ScopedTypeVariables #-}
12-- Module : Streamly.Internal.Memory.Array
13-- Copyright : (c) 2019 Composewell Technologies
16-- Maintainer : streamly@composewell.com
17-- Stability : experimental
22-- * Arrays are finite and fixed in size
23-- * provide /O(1)/ access to elements
24-- * store only data and not functions
25-- * provide efficient IO interfacing
27-- 'Foldable' instance is not provided because the implementation would be much
28-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
29-- instances should be used with care; concatenating arrays using binary
30-- operations can be highly inefficient. Instead, use
31-- 'Streamly.Internal.Memory.ArrayStream.toArray' to concatenate N arrays at
34-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
35-- single byte) are only as good as holding those elements in a Haskell list.
36-- However, small arrays can be compacted into large ones to reduce the
37-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
38-- if we use one array for each chunk. This is still significant to add
41module Streamly.Internal.Memory.Array
59 , A.writeN -- drop new
60 , A.write -- full buffer
61 -- , writeLastN -- drop old (ring buffer)
80 -- , readFrom -- read from a given position to the end of file
81 -- , readFromRev -- read from a given position to the beginning of file
82 -- , readTo -- read from beginning up to the given position
83 -- , readToRev -- read from end to the given position in file
91 -- , writeFrom -- start writing at the given position
93 -- , writeTo -- write from beginning up to the given position
98 -- , writeChunksOfFrom
112 -- -- * In-pace mutation (for Mutable Array type)
118 -- * Immutable Transformations
127import Control.Monad.IO.Class (MonadIO(..))
128-- import Data.Functor.Identity (Identity)
129import Foreign.ForeignPtr (withForeignPtr, touchForeignPtr)
130import Foreign.Ptr (plusPtr)
131import Foreign.Storable (Storable(..))
132import Prelude hiding (length, null, last, map, (!!), read, concat)
134import GHC.ForeignPtr (ForeignPtr(..))
135import GHC.Ptr (Ptr(..))
137import Streamly.Internal.Data.Fold.Types (Fold(..))
138import Streamly.Internal.Data.Unfold.Types (Unfold(..))
139import Streamly.Internal.Memory.Array.Types (Array(..), length)
140import Streamly.Streams.Serial (SerialT)
141import Streamly.Streams.StreamK.Type (IsStream)
143import qualified Streamly.Internal.Memory.Array.Types as A
144import qualified Streamly.Streams.Prelude as P
145import qualified Streamly.Streams.Serial as Serial
146import qualified Streamly.Streams.StreamD as D
147import qualified Streamly.Streams.StreamK as K
149-------------------------------------------------------------------------------
151-------------------------------------------------------------------------------
154-- | Create a new uninitialized array of given length.
157newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
158newArray len = undefined
161-- | Create an 'Array' from the first N elements of a stream. The array is
162-- allocated to size N, if the stream terminates before N elements then the
163-- array may hold less than N elements.
166{-# INLINE fromStreamN #-}
167fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
169 if n < 0 then error "writeN: negative write count specified" else return ()
170 A.fromStreamDN n $ D.toStreamD m
172-- | Create an 'Array' from a stream. This is useful when we want to create a
173-- single array from a stream of unknown size. 'writeN' is at least twice
174-- as efficient when the size is already known.
176-- Note that if the input stream is too large memory allocation for the array
177-- may fail. When the stream size is not known, `arraysOf` followed by
178-- processing of indvidual arrays in the resulting stream should be preferred.
181{-# INLINE fromStream #-}
182fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
183fromStream = P.runFold A.write
184-- write m = A.fromStreamD $ D.toStreamD m
186-------------------------------------------------------------------------------
188-------------------------------------------------------------------------------
190-- | Convert an 'Array' into a stream.
193{-# INLINE_EARLY toStream #-}
194toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
195toStream = D.fromStreamD . A.toStreamD
196-- XXX add fallback to StreamK rule
197-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
198-- forall a. S.readK (read a) = K.fromArray a #-}
200-- | Convert an 'Array' into a stream in reverse order.
203{-# INLINE_EARLY toStreamRev #-}
204toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
205toStreamRev = D.fromStreamD . A.toStreamDRev
206-- XXX add fallback to StreamK rule
207-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
208-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
210data ReadUState a = ReadUState
211 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
212 {-# UNPACK #-} !(Ptr a) -- current pointer
214-- | Unfold an array into a stream.
217{-# INLINE_NORMAL read #-}
218read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
219read = Unfold step inject
222 inject (Array (ForeignPtr start contents) (Ptr end) _) =
223 return $ ReadUState (ForeignPtr end contents) (Ptr start)
225 {-# INLINE_LATE step #-}
226 step (ReadUState fp@(ForeignPtr end _) p) | p == (Ptr end) =
227 let x = A.unsafeInlineIO $ touchForeignPtr fp
228 in x `seq` return D.Stop
229 step (ReadUState fp p) = do
230 -- unsafeInlineIO allows us to run this in Identity monad for pure
231 -- toList/foldr case which makes them much faster due to not
232 -- accumulating the list and fusing better with the pure consumers.
234 -- This should be safe as the array contents are guaranteed to be
235 -- evaluated/written to before we peek at them.
236 let !x = A.unsafeInlineIO $ peek p
238 (ReadUState fp (p `plusPtr` (sizeOf (undefined :: a))))
240-- | > null arr = length arr == 0
244null :: Storable a => Array a -> Bool
245null arr = length arr == 0
247-- | > last arr = readIndex arr (length arr - 1)
251last :: Storable a => Array a -> Maybe a
252last arr = readIndex arr (length arr - 1)
254-------------------------------------------------------------------------------
256-------------------------------------------------------------------------------
258-------------------------------------------------------------------------------
260-------------------------------------------------------------------------------
263-- | Perform a binary search in the array to find an element.
264bsearch :: a -> Array a -> Maybe Bool
267-- | Perform a binary search in the array to find an element index.
268{-# INLINE elemIndex #-}
269bsearchIndex :: a -> Array a -> Maybe Int
270bsearchIndex elem arr = undefined
272-- find/findIndex etc can potentially be implemented more efficiently on arrays
273-- compared to streams by using SIMD instructions.
275find :: (a -> Bool) -> Array a -> Bool
278findIndex :: (a -> Bool) -> Array a -> Maybe Int
281findIndices :: (a -> Bool) -> Array a -> Array Int
282findIndices = undefined
285-------------------------------------------------------------------------------
287-------------------------------------------------------------------------------
289-- XXX We can potentially use SIMD instructions on arrays to fold faster.
291-------------------------------------------------------------------------------
293-------------------------------------------------------------------------------
296slice :: Int -> Int -> Array a
297slice begin end arr = undefined
299splitAt :: Int -> Array a -> (Array a, Array a)
300splitAt i arr = undefined
302-- XXX This operation can be performed efficiently via streams.
303-- | Append two arrays together to create a single array.
304splice :: Array a -> Array a -> Array a
305splice arr1 arr2 = undefined
307-------------------------------------------------------------------------------
308-- In-place mutation APIs
309-------------------------------------------------------------------------------
311-- | Partition an array into two halves using a partitioning predicate. The
312-- first half retains values where the predicate is 'False' and the second half
313-- retains values where the predicate is 'True'.
314{-# INLINE partitionBy #-}
315partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
316partitionBy f arr = undefined
318-- | Shuffle corresponding elements from two arrays using a shuffle function.
319-- If the shuffle function returns 'False' then do nothing otherwise swap the
320-- elements. This can be used in a bottom up fold to shuffle or reorder the
322shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
323shuffleBy f arr1 arr2 = undefined
325-- XXX we can also make the folds partial by stopping at a certain level.
327-- | Perform a top down hierarchical recursive partitioning fold of items in
328-- the container using the given function as the partition function.
330-- This will perform a quick sort if the partition function is
331-- 'partitionBy (< pivot)'.
334{-# INLINABLE foldtWith #-}
335foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
336foldtWith level f = undefined
338-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
339-- indicates the level in the tree where the fold would stop.
341-- This will perform a random shuffle if the shuffle function is random.
342-- If we stop at level 0 and repeatedly apply the function then we can do a
344foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
345foldbWith level f = undefined
348-- XXX consider the bulk update/accumulation/permutation APIs from vector.
350-------------------------------------------------------------------------------
351-- Random reads and writes
352-------------------------------------------------------------------------------
354-- | /O(1)/ Lookup the element at the given index, starting from 0.
357{-# INLINE readIndex #-}
358readIndex :: Storable a => Array a -> Int -> Maybe a
360 if i < 0 || i > length arr - 1
362 else A.unsafeInlineIO $
363 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
366-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
367-- at index @i@ and reading up to @count@ elements in the forward direction
368-- ending at the index @i + count - 1@.
371{-# INLINE readSlice #-}
372readSlice :: (IsStream t, Monad m, Storable a)
373 => Array a -> Int -> Int -> t m a
374readSlice arr i len = undefined
376-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
377-- index @i@ and reading up to @count@ elements in the reverse direction ending
378-- at the index @i - count + 1@.
381{-# INLINE readSliceRev #-}
382readSliceRev :: (IsStream t, Monad m, Storable a)
383 => Array a -> Int -> Int -> t m a
384readSliceRev arr i len = undefined
387-- | /O(1)/ Write the given element at the given index in the array.
388-- Performs in-place mutation of the array.
391{-# INLINE writeIndex #-}
392writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
393writeIndex arr i a = do
394 let maxIndex = length arr - 1
396 then error "writeIndex: negative array index"
398 then error $ "writeIndex: specified array index " ++ show i
399 ++ " is beyond the maximum index " ++ show maxIndex
401 liftIO $ withForeignPtr (aStart arr) $ \p ->
405-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
406-- starting at index @i@ and writing up to @count@ elements in the forward
407-- direction ending at the index @i + count - 1@.
410{-# INLINE writeSlice #-}
411writeSlice :: (IsStream t, Monad m, Storable a)
412 => Array a -> Int -> Int -> t m a -> m ()
413writeSlice arr i len s = undefined
415-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
416-- starting at index @i@ and writing up to @count@ elements in the reverse
417-- direction ending at the index @i - count + 1@.
420{-# INLINE writeSliceRev #-}
421writeSliceRev :: (IsStream t, Monad m, Storable a)
422 => Array a -> Int -> Int -> t m a -> m ()
423writeSliceRev arr i len s = undefined
426-------------------------------------------------------------------------------
427-- Transform via stream operations
428-------------------------------------------------------------------------------
430-- for non-length changing operations we can use the original length for
431-- allocation. If we can predict the length then we can use the prediction for
432-- new allocation. Otherwise we can use a hint and adjust dynamically.
435-- | Transform an array into another array using a pipe transformation
439{-# INLINE runPipe #-}
440runPipe :: (MonadIO m, Storable a, Storable b)
441 => Pipe m a b -> Array a -> m (Array b)
442runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
445-- | Transform an array into another array using a stream transformation
449{-# INLINE streamTransform #-}
450streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
451 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
452streamTransform f arr =
453 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
456-- | Fold an array using a 'Fold'.
460fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
461fold f arr = P.runFold f $ (toStream arr :: Serial.SerialT m a)
463-- | Fold an array using a stream fold operation.
466{-# INLINE streamFold #-}
467streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
468streamFold 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