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)
83 -- , readFrom -- read from a given position to the end of file
84 -- , readFromRev -- read from a given position to the beginning of file
85 -- , readTo -- read from beginning up to the given position
86 -- , readToRev -- read from end to the given position in file
94 -- , writeFrom -- start writing at the given position
96 -- , writeTo -- write from beginning up to the given position
101 -- , writeChunksOfFrom
115 -- -- * In-pace mutation (for Mutable Array type)
121 -- * Immutable Transformations
130import Control.Monad.IO.Class (MonadIO(..))
131-- import Data.Functor.Identity (Identity)
132import Foreign.ForeignPtr (withForeignPtr, touchForeignPtr)
133import Foreign.Ptr (plusPtr)
134import Foreign.Storable (Storable(..))
135import Prelude hiding (length, null, last, map, (!!), read, concat)
137import GHC.ForeignPtr (ForeignPtr(..))
138import GHC.Ptr (Ptr(..))
139import GHC.Prim (touch#)
140import GHC.IO (IO(..))
142import Streamly.Internal.Data.Fold.Types (Fold(..))
143import Streamly.Internal.Data.Unfold.Types (Unfold(..))
144import Streamly.Internal.Memory.Array.Types (Array(..), length)
145import Streamly.Internal.Data.Stream.Serial (SerialT)
146import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
148import qualified Streamly.Internal.Memory.Array.Types as A
149import qualified Streamly.Internal.Data.Stream.Prelude as P
150import qualified Streamly.Internal.Data.Stream.Serial as Serial
151import qualified Streamly.Internal.Data.Stream.StreamD as D
152import qualified Streamly.Internal.Data.Stream.StreamK as K
154-------------------------------------------------------------------------------
156-------------------------------------------------------------------------------
159-- | Create a new uninitialized array of given length.
162newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
163newArray len = undefined
166-- | Create an 'Array' from the first N elements of a stream. The array is
167-- allocated to size N, if the stream terminates before N elements then the
168-- array may hold less than N elements.
171{-# INLINE fromStreamN #-}
172fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
174 if n < 0 then error "writeN: negative write count specified" else return ()
175 A.fromStreamDN n $ D.toStreamD m
177-- | Create an 'Array' from a stream. This is useful when we want to create a
178-- single array from a stream of unknown size. 'writeN' is at least twice
179-- as efficient when the size is already known.
181-- Note that if the input stream is too large memory allocation for the array
182-- may fail. When the stream size is not known, `arraysOf` followed by
183-- processing of indvidual arrays in the resulting stream should be preferred.
186{-# INLINE fromStream #-}
187fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
188fromStream = P.runFold A.write
189-- write m = A.fromStreamD $ D.toStreamD m
191-------------------------------------------------------------------------------
193-------------------------------------------------------------------------------
195-- | Convert an 'Array' into a stream.
198{-# INLINE_EARLY toStream #-}
199toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
200toStream = D.fromStreamD . A.toStreamD
201-- XXX add fallback to StreamK rule
202-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
203-- forall a. S.readK (read a) = K.fromArray a #-}
205-- | Convert an 'Array' into a stream in reverse order.
208{-# INLINE_EARLY toStreamRev #-}
209toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
210toStreamRev = D.fromStreamD . A.toStreamDRev
211-- XXX add fallback to StreamK rule
212-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
213-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
215data ReadUState a = ReadUState
216 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
217 {-# UNPACK #-} !(Ptr a) -- current pointer
219-- | Unfold an array into a stream.
222{-# INLINE_NORMAL read #-}
223read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
224read = Unfold step inject
227 inject (Array (ForeignPtr start contents) (Ptr end) _) =
228 return $ ReadUState (ForeignPtr end contents) (Ptr start)
230 {-# INLINE_LATE step #-}
231 step (ReadUState fp@(ForeignPtr end _) p) | p == (Ptr end) =
232 let x = A.unsafeInlineIO $ touchForeignPtr fp
233 in x `seq` return D.Stop
234 step (ReadUState fp p) = do
235 -- unsafeInlineIO allows us to run this in Identity monad for pure
236 -- toList/foldr case which makes them much faster due to not
237 -- accumulating the list and fusing better with the pure consumers.
239 -- This should be safe as the array contents are guaranteed to be
240 -- evaluated/written to before we peek at them.
241 let !x = A.unsafeInlineIO $ peek p
243 (ReadUState fp (p `plusPtr` (sizeOf (undefined :: a))))
245-- | Unfold an array into a stream, does not check the end of the array, the
246-- user is responsible for terminating the stream within the array bounds. For
247-- high performance application where the end condition can be determined by
248-- a terminating fold.
250-- Written in the hope that it may be faster than "read", however, in the case
251-- for which this was written, "read" proves to be faster even though the core
252-- generated with unsafeRead looks simpler.
256{-# INLINE_NORMAL unsafeRead #-}
257unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
258unsafeRead = Unfold step inject
261 inject (Array fp _ _) = return fp
263 {-# INLINE_LATE step #-}
264 step (ForeignPtr p contents) = do
265 -- unsafeInlineIO allows us to run this in Identity monad for pure
266 -- toList/foldr case which makes them much faster due to not
267 -- accumulating the list and fusing better with the pure consumers.
269 -- This should be safe as the array contents are guaranteed to be
270 -- evaluated/written to before we peek at them.
271 let !x = A.unsafeInlineIO $ do
275 let !(Ptr p1) = Ptr p `plusPtr` (sizeOf (undefined :: a))
276 return $ D.Yield x (ForeignPtr p1 contents)
278 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
280-- | > null arr = length arr == 0
284null :: Storable a => Array a -> Bool
285null arr = length arr == 0
287-- | > last arr = readIndex arr (length arr - 1)
291last :: Storable a => Array a -> Maybe a
292last arr = readIndex arr (length arr - 1)
294-------------------------------------------------------------------------------
296-------------------------------------------------------------------------------
298-------------------------------------------------------------------------------
300-------------------------------------------------------------------------------
303-- | Perform a binary search in the array to find an element.
304bsearch :: a -> Array a -> Maybe Bool
307-- | Perform a binary search in the array to find an element index.
308{-# INLINE elemIndex #-}
309bsearchIndex :: a -> Array a -> Maybe Int
310bsearchIndex elem arr = undefined
312-- find/findIndex etc can potentially be implemented more efficiently on arrays
313-- compared to streams by using SIMD instructions.
315find :: (a -> Bool) -> Array a -> Bool
318findIndex :: (a -> Bool) -> Array a -> Maybe Int
321findIndices :: (a -> Bool) -> Array a -> Array Int
322findIndices = undefined
325-------------------------------------------------------------------------------
327-------------------------------------------------------------------------------
329-- XXX We can potentially use SIMD instructions on arrays to fold faster.
331-------------------------------------------------------------------------------
333-------------------------------------------------------------------------------
336slice :: Int -> Int -> Array a
337slice begin end arr = undefined
339splitAt :: Int -> Array a -> (Array a, Array a)
340splitAt i arr = undefined
342-- XXX This operation can be performed efficiently via streams.
343-- | Append two arrays together to create a single array.
344splice :: Array a -> Array a -> Array a
345splice arr1 arr2 = undefined
347-------------------------------------------------------------------------------
348-- In-place mutation APIs
349-------------------------------------------------------------------------------
351-- | Partition an array into two halves using a partitioning predicate. The
352-- first half retains values where the predicate is 'False' and the second half
353-- retains values where the predicate is 'True'.
354{-# INLINE partitionBy #-}
355partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
356partitionBy f arr = undefined
358-- | Shuffle corresponding elements from two arrays using a shuffle function.
359-- If the shuffle function returns 'False' then do nothing otherwise swap the
360-- elements. This can be used in a bottom up fold to shuffle or reorder the
362shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
363shuffleBy f arr1 arr2 = undefined
365-- XXX we can also make the folds partial by stopping at a certain level.
367-- | Perform a top down hierarchical recursive partitioning fold of items in
368-- the container using the given function as the partition function.
370-- This will perform a quick sort if the partition function is
371-- 'partitionBy (< pivot)'.
374{-# INLINABLE foldtWith #-}
375foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
376foldtWith level f = undefined
378-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
379-- indicates the level in the tree where the fold would stop.
381-- This will perform a random shuffle if the shuffle function is random.
382-- If we stop at level 0 and repeatedly apply the function then we can do a
384foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
385foldbWith level f = undefined
388-- XXX consider the bulk update/accumulation/permutation APIs from vector.
390-------------------------------------------------------------------------------
391-- Random reads and writes
392-------------------------------------------------------------------------------
394-- | /O(1)/ Lookup the element at the given index, starting from 0.
397{-# INLINE readIndex #-}
398readIndex :: Storable a => Array a -> Int -> Maybe a
400 if i < 0 || i > length arr - 1
402 else A.unsafeInlineIO $
403 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
406-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
407-- at index @i@ and reading up to @count@ elements in the forward direction
408-- ending at the index @i + count - 1@.
411{-# INLINE readSlice #-}
412readSlice :: (IsStream t, Monad m, Storable a)
413 => Array a -> Int -> Int -> t m a
414readSlice arr i len = undefined
416-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
417-- index @i@ and reading up to @count@ elements in the reverse direction ending
418-- at the index @i - count + 1@.
421{-# INLINE readSliceRev #-}
422readSliceRev :: (IsStream t, Monad m, Storable a)
423 => Array a -> Int -> Int -> t m a
424readSliceRev arr i len = undefined
427-- | /O(1)/ Write the given element at the given index in the array.
428-- Performs in-place mutation of the array.
431{-# INLINE writeIndex #-}
432writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
433writeIndex arr i a = do
434 let maxIndex = length arr - 1
436 then error "writeIndex: negative array index"
438 then error $ "writeIndex: specified array index " ++ show i
439 ++ " is beyond the maximum index " ++ show maxIndex
441 liftIO $ withForeignPtr (aStart arr) $ \p ->
445-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
446-- starting at index @i@ and writing up to @count@ elements in the forward
447-- direction ending at the index @i + count - 1@.
450{-# INLINE writeSlice #-}
451writeSlice :: (IsStream t, Monad m, Storable a)
452 => Array a -> Int -> Int -> t m a -> m ()
453writeSlice arr i len s = undefined
455-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
456-- starting at index @i@ and writing up to @count@ elements in the reverse
457-- direction ending at the index @i - count + 1@.
460{-# INLINE writeSliceRev #-}
461writeSliceRev :: (IsStream t, Monad m, Storable a)
462 => Array a -> Int -> Int -> t m a -> m ()
463writeSliceRev arr i len s = undefined
466-------------------------------------------------------------------------------
467-- Transform via stream operations
468-------------------------------------------------------------------------------
470-- for non-length changing operations we can use the original length for
471-- allocation. If we can predict the length then we can use the prediction for
472-- new allocation. Otherwise we can use a hint and adjust dynamically.
475-- | Transform an array into another array using a pipe transformation
479{-# INLINE runPipe #-}
480runPipe :: (MonadIO m, Storable a, Storable b)
481 => Pipe m a b -> Array a -> m (Array b)
482runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
485-- | Transform an array into another array using a stream transformation
489{-# INLINE streamTransform #-}
490streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
491 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
492streamTransform f arr =
493 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
496-- | Fold an array using a 'Fold'.
500fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
501fold f arr = P.runFold f $ (toStream arr :: Serial.SerialT m a)
503-- | Fold an array using a stream fold operation.
506{-# INLINE streamFold #-}
507streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
508streamFold 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