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
61 , A.write -- full buffer
62 -- , writeLastN -- drop old (ring buffer)
82 -- , readFrom -- read from a given position to the end of file
83 -- , readFromRev -- read from a given position to the beginning of file
84 -- , readTo -- read from beginning up to the given position
85 -- , readToRev -- read from end to the given position in file
93 -- , writeFrom -- start writing at the given position
95 -- , writeTo -- write from beginning up to the given position
100 -- , writeChunksOfFrom
114 -- -- * In-pace mutation (for Mutable Array type)
120 -- * Immutable Transformations
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(..))
139import Streamly.Internal.Data.Fold.Types (Fold(..))
140import Streamly.Internal.Data.Unfold.Types (Unfold(..))
141import Streamly.Internal.Memory.Array.Types (Array(..), length)
142import Streamly.Streams.Serial (SerialT)
143import Streamly.Streams.StreamK.Type (IsStream)
145import qualified Streamly.Internal.Memory.Array.Types as A
146import qualified Streamly.Streams.Prelude as P
147import qualified Streamly.Streams.Serial as Serial
148import qualified Streamly.Streams.StreamD as D
149import qualified Streamly.Streams.StreamK as K
151-------------------------------------------------------------------------------
153-------------------------------------------------------------------------------
156-- | Create a new uninitialized array of given length.
159newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
160newArray len = undefined
163-- | Create an 'Array' from the first N elements of a stream. The array is
164-- allocated to size N, if the stream terminates before N elements then the
165-- array may hold less than N elements.
168{-# INLINE fromStreamN #-}
169fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
171 if n < 0 then error "writeN: negative write count specified" else return ()
172 A.fromStreamDN n $ D.toStreamD m
174-- | Create an 'Array' from a stream. This is useful when we want to create a
175-- single array from a stream of unknown size. 'writeN' is at least twice
176-- as efficient when the size is already known.
178-- Note that if the input stream is too large memory allocation for the array
179-- may fail. When the stream size is not known, `arraysOf` followed by
180-- processing of indvidual arrays in the resulting stream should be preferred.
183{-# INLINE fromStream #-}
184fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
185fromStream = P.runFold A.write
186-- write m = A.fromStreamD $ D.toStreamD m
188-------------------------------------------------------------------------------
190-------------------------------------------------------------------------------
192-- | Convert an 'Array' into a stream.
195{-# INLINE_EARLY toStream #-}
196toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
197toStream = D.fromStreamD . A.toStreamD
198-- XXX add fallback to StreamK rule
199-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
200-- forall a. S.readK (read a) = K.fromArray a #-}
202-- | Convert an 'Array' into a stream in reverse order.
205{-# INLINE_EARLY toStreamRev #-}
206toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
207toStreamRev = D.fromStreamD . A.toStreamDRev
208-- XXX add fallback to StreamK rule
209-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
210-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
212data ReadUState a = ReadUState
213 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
214 {-# UNPACK #-} !(Ptr a) -- current pointer
216-- | Unfold an array into a stream.
219{-# INLINE_NORMAL read #-}
220read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
221read = Unfold step inject
224 inject (Array (ForeignPtr start contents) (Ptr end) _) =
225 return $ ReadUState (ForeignPtr end contents) (Ptr start)
227 {-# INLINE_LATE step #-}
228 step (ReadUState fp@(ForeignPtr end _) p) | p == (Ptr end) =
229 let x = A.unsafeInlineIO $ touchForeignPtr fp
230 in x `seq` return D.Stop
231 step (ReadUState fp p) = do
232 -- unsafeInlineIO allows us to run this in Identity monad for pure
233 -- toList/foldr case which makes them much faster due to not
234 -- accumulating the list and fusing better with the pure consumers.
236 -- This should be safe as the array contents are guaranteed to be
237 -- evaluated/written to before we peek at them.
238 let !x = A.unsafeInlineIO $ peek p
240 (ReadUState fp (p `plusPtr` (sizeOf (undefined :: a))))
242-- | > null arr = length arr == 0
246null :: Storable a => Array a -> Bool
247null arr = length arr == 0
249-- | > last arr = readIndex arr (length arr - 1)
253last :: Storable a => Array a -> Maybe a
254last arr = readIndex arr (length arr - 1)
256-------------------------------------------------------------------------------
258-------------------------------------------------------------------------------
260-------------------------------------------------------------------------------
262-------------------------------------------------------------------------------
265-- | Perform a binary search in the array to find an element.
266bsearch :: a -> Array a -> Maybe Bool
269-- | Perform a binary search in the array to find an element index.
270{-# INLINE elemIndex #-}
271bsearchIndex :: a -> Array a -> Maybe Int
272bsearchIndex elem arr = undefined
274-- find/findIndex etc can potentially be implemented more efficiently on arrays
275-- compared to streams by using SIMD instructions.
277find :: (a -> Bool) -> Array a -> Bool
280findIndex :: (a -> Bool) -> Array a -> Maybe Int
283findIndices :: (a -> Bool) -> Array a -> Array Int
284findIndices = undefined
287-------------------------------------------------------------------------------
289-------------------------------------------------------------------------------
291-- XXX We can potentially use SIMD instructions on arrays to fold faster.
293-------------------------------------------------------------------------------
295-------------------------------------------------------------------------------
298slice :: Int -> Int -> Array a
299slice begin end arr = undefined
301splitAt :: Int -> Array a -> (Array a, Array a)
302splitAt i arr = undefined
304-- XXX This operation can be performed efficiently via streams.
305-- | Append two arrays together to create a single array.
306splice :: Array a -> Array a -> Array a
307splice arr1 arr2 = undefined
309-------------------------------------------------------------------------------
310-- In-place mutation APIs
311-------------------------------------------------------------------------------
313-- | Partition an array into two halves using a partitioning predicate. The
314-- first half retains values where the predicate is 'False' and the second half
315-- retains values where the predicate is 'True'.
316{-# INLINE partitionBy #-}
317partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
318partitionBy f arr = undefined
320-- | Shuffle corresponding elements from two arrays using a shuffle function.
321-- If the shuffle function returns 'False' then do nothing otherwise swap the
322-- elements. This can be used in a bottom up fold to shuffle or reorder the
324shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
325shuffleBy f arr1 arr2 = undefined
327-- XXX we can also make the folds partial by stopping at a certain level.
329-- | Perform a top down hierarchical recursive partitioning fold of items in
330-- the container using the given function as the partition function.
332-- This will perform a quick sort if the partition function is
333-- 'partitionBy (< pivot)'.
336{-# INLINABLE foldtWith #-}
337foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
338foldtWith level f = undefined
340-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
341-- indicates the level in the tree where the fold would stop.
343-- This will perform a random shuffle if the shuffle function is random.
344-- If we stop at level 0 and repeatedly apply the function then we can do a
346foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
347foldbWith level f = undefined
350-- XXX consider the bulk update/accumulation/permutation APIs from vector.
352-------------------------------------------------------------------------------
353-- Random reads and writes
354-------------------------------------------------------------------------------
356-- | /O(1)/ Lookup the element at the given index, starting from 0.
359{-# INLINE readIndex #-}
360readIndex :: Storable a => Array a -> Int -> Maybe a
362 if i < 0 || i > length arr - 1
364 else A.unsafeInlineIO $
365 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
368-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
369-- at index @i@ and reading up to @count@ elements in the forward direction
370-- ending at the index @i + count - 1@.
373{-# INLINE readSlice #-}
374readSlice :: (IsStream t, Monad m, Storable a)
375 => Array a -> Int -> Int -> t m a
376readSlice arr i len = undefined
378-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
379-- index @i@ and reading up to @count@ elements in the reverse direction ending
380-- at the index @i - count + 1@.
383{-# INLINE readSliceRev #-}
384readSliceRev :: (IsStream t, Monad m, Storable a)
385 => Array a -> Int -> Int -> t m a
386readSliceRev arr i len = undefined
389-- | /O(1)/ Write the given element at the given index in the array.
390-- Performs in-place mutation of the array.
393{-# INLINE writeIndex #-}
394writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
395writeIndex arr i a = do
396 let maxIndex = length arr - 1
398 then error "writeIndex: negative array index"
400 then error $ "writeIndex: specified array index " ++ show i
401 ++ " is beyond the maximum index " ++ show maxIndex
403 liftIO $ withForeignPtr (aStart arr) $ \p ->
407-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
408-- starting at index @i@ and writing up to @count@ elements in the forward
409-- direction ending at the index @i + count - 1@.
412{-# INLINE writeSlice #-}
413writeSlice :: (IsStream t, Monad m, Storable a)
414 => Array a -> Int -> Int -> t m a -> m ()
415writeSlice arr i len s = undefined
417-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
418-- starting at index @i@ and writing up to @count@ elements in the reverse
419-- direction ending at the index @i - count + 1@.
422{-# INLINE writeSliceRev #-}
423writeSliceRev :: (IsStream t, Monad m, Storable a)
424 => Array a -> Int -> Int -> t m a -> m ()
425writeSliceRev arr i len s = undefined
428-------------------------------------------------------------------------------
429-- Transform via stream operations
430-------------------------------------------------------------------------------
432-- for non-length changing operations we can use the original length for
433-- allocation. If we can predict the length then we can use the prediction for
434-- new allocation. Otherwise we can use a hint and adjust dynamically.
437-- | Transform an array into another array using a pipe transformation
441{-# INLINE runPipe #-}
442runPipe :: (MonadIO m, Storable a, Storable b)
443 => Pipe m a b -> Array a -> m (Array b)
444runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
447-- | Transform an array into another array using a stream transformation
451{-# INLINE streamTransform #-}
452streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
453 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
454streamTransform f arr =
455 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
458-- | Fold an array using a 'Fold'.
462fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
463fold f arr = P.runFold f $ (toStream arr :: Serial.SerialT m a)
465-- | Fold an array using a stream fold operation.
468{-# INLINE streamFold #-}
469streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
470streamFold 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