2-- Module : Streamly.Internal.Data.Array
3-- Copyright : (c) 2019 Composewell Technologies
6-- Maintainer : streamly@composewell.com
7-- Stability : experimental
12-- * Arrays are finite and fixed in size
13-- * provide /O(1)/ access to elements
14-- * store only data and not functions
15-- * provide efficient IO interfacing
17-- 'Foldable' instance is not provided because the implementation would be much
18-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
19-- instances should be used with care; concatenating arrays using binary
20-- operations can be highly inefficient. Instead, use
21-- 'Streamly.Internal.Data.Stream.Chunked.toArray' to concatenate N
24-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
25-- single byte) are only as good as holding those elements in a Haskell list.
26-- However, small arrays can be compacted into large ones to reduce the
27-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
28-- if we use one array for each chunk. This is still significant to add
31module Streamly.Internal.Data.Array
46 , A.writeN -- drop new
48 , A.write -- full buffer
63 , producer -- experimental
68 , A.unsafeIndex -- XXX Rename to getIndexUnsafe??
70 , last -- XXX getIndexLast?
72 , getIndicesFromThenTo
73 -- , getIndicesFrom -- read from a given position to the end of file
74 -- , getIndicesUpto -- read from beginning up to the given position
76 -- , getIndicesFromRev -- read from a given position to the beginning of file
77 -- , getIndicesUptoRev -- read from end to the given position in file
95 , A.unsafeFreeze -- asImmutableUnsafe?
96 , A.unsafeThaw -- asMutableUnsafe?
105 -- * Streaming Operations
119#include "ArrayMacros.h"
121import Control.Exception (assert)
122import Control.Monad (when)
123import Control.Monad.IO.Class (MonadIO(..))
124import Data.Functor.Identity (Identity)
125import Data.Word (Word8)
126import Foreign.C.String (CString)
127import Foreign.Ptr (castPtr)
128import Streamly.Internal.Data.Unboxed
134import Prelude hiding (length, null, last, map, (!!), read, concat)
136import Streamly.Internal.Data.Array.Mut.Type (ArrayUnsafe(..))
137import Streamly.Internal.Data.Array.Type
138 (Array(..), length, asPtrUnsafe)
139import Streamly.Internal.Data.Fold.Type (Fold(..))
140import Streamly.Internal.Data.Producer.Type (Producer(..))
141import Streamly.Internal.Data.Stream (Stream)
142import Streamly.Internal.Data.Tuple.Strict (Tuple3Fused'(..))
143import Streamly.Internal.Data.Unfold.Type (Unfold(..))
144import Streamly.Internal.System.IO (unsafeInlineIO)
146import qualified Streamly.Internal.Data.Array.Mut.Type as MA
147import qualified Streamly.Internal.Data.Array.Mut as MA
148import qualified Streamly.Internal.Data.Array.Type as A
149import qualified Streamly.Internal.Data.Fold as FL
150import qualified Streamly.Internal.Data.Producer.Type as Producer
151import qualified Streamly.Internal.Data.Producer as Producer
152import qualified Streamly.Internal.Data.Ring.Unboxed as RB
153import qualified Streamly.Internal.Data.Stream.Common as P
154import qualified Streamly.Internal.Data.Stream.StreamD as D
155import qualified Streamly.Internal.Data.Stream.Type as Stream
156import qualified Streamly.Internal.Data.Unfold as Unfold
158-------------------------------------------------------------------------------
160-------------------------------------------------------------------------------
162-- | Create an 'Array' from the first N elements of a stream. The array is
163-- allocated to size N, if the stream terminates before N elements then the
164-- array may hold less than N elements.
167{-# INLINE fromStreamN #-}
168fromStreamN :: (MonadIO m, Unbox a) => Int -> Stream m a -> m (Array a)
170 when (n < 0) $ error "writeN: negative write count specified"
171 A.fromStreamDN n $ Stream.toStreamD m
173-- | Create an 'Array' from a stream. This is useful when we want to create a
174-- single array from a stream of unknown size. 'writeN' is at least twice
175-- as efficient when the size is already known.
177-- Note that if the input stream is too large memory allocation for the array
178-- may fail. When the stream size is not known, `arraysOf` followed by
179-- processing of indvidual arrays in the resulting stream should be preferred.
182{-# INLINE fromStream #-}
183fromStream :: (MonadIO m, Unbox a) => Stream m a -> m (Array a)
184fromStream m = P.fold A.write $ Stream.toStreamK m
185-- write m = A.fromStreamD $ D.fromStreamK m
187-------------------------------------------------------------------------------
189-------------------------------------------------------------------------------
191{-# INLINE_NORMAL producer #-}
192producer :: forall m a. (Monad m, Unbox a) => Producer m (Array a) a
194 Producer.translate A.unsafeThaw A.unsafeFreeze
195 $ MA.producerWith (return . unsafeInlineIO)
197-- | Unfold an array into a stream.
199{-# INLINE_NORMAL reader #-}
200reader :: forall m a. (Monad m, Unbox a) => Unfold m (Array a) a
201reader = Producer.simplify producer
203-- | Unfold an array into a stream, does not check the end of the array, the
204-- user is responsible for terminating the stream within the array bounds. For
205-- high performance application where the end condition can be determined by
206-- a terminating fold.
208-- Written in the hope that it may be faster than "read", however, in the case
209-- for which this was written, "read" proves to be faster even though the core
210-- generated with unsafeRead looks simpler.
214{-# INLINE_NORMAL readerUnsafe #-}
215readerUnsafe :: forall m a. (Monad m, Unbox a) => Unfold m (Array a) a
216readerUnsafe = Unfold step inject
219 inject (Array contents start end) =
220 return (ArrayUnsafe contents end start)
222 {-# INLINE_LATE step #-}
223 step (ArrayUnsafe contents end p) = do
224 -- unsafeInlineIO allows us to run this in Identity monad for pure
225 -- toList/foldr case which makes them much faster due to not
226 -- accumulating the list and fusing better with the pure consumers.
228 -- This should be safe as the array contents are guaranteed to be
229 -- evaluated/written to before we peek at them.
230 let !x = unsafeInlineIO $ peekWith contents p
231 let !p1 = INDEX_NEXT(p,a)
232 return $ D.Yield x (ArrayUnsafe contents end p1)
236-- >>> import qualified Streamly.Internal.Data.Array.Type as Array
237-- >>> null arr = Array.byteLength arr == 0
241null :: Array a -> Bool
242null arr = A.byteLength arr == 0
244-- | Like 'getIndex' but indexes the array in reverse from the end.
247{-# INLINE getIndexRev #-}
248getIndexRev :: forall a. Unbox a => Int -> Array a -> Maybe a
252 let elemPtr = RINDEX_OF(arrEnd arr, i, a)
253 if i >= 0 && elemPtr >= arrStart arr
254 then Just <$> peekWith (arrContents arr) elemPtr
259-- >>> import qualified Streamly.Internal.Data.Array as Array
260-- >>> last arr = Array.getIndexRev arr 0
264last :: Unbox a => Array a -> Maybe a
267-------------------------------------------------------------------------------
268-- Folds with Array as the container
269-------------------------------------------------------------------------------
271-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
272-- stream to an 'Array'.
274{-# INLINE writeLastN #-}
276 (Unbox a, MonadIO m) => Int -> Fold m a (Array a)
278 | n <= 0 = fmap (const mempty) FL.drain
279 | otherwise = A.unsafeFreeze <$> Fold step initial done
283 step (Tuple3Fused' rb rh i) a = do
284 rh1 <- liftIO $ RB.unsafeInsert rb rh a
285 return $ FL.Partial $ Tuple3Fused' rb rh1 (i + 1)
288 let f (a, b) = FL.Partial $ Tuple3Fused' a b (0 :: Int)
289 in fmap f $ liftIO $ RB.new n
291 done (Tuple3Fused' rb rh i) = do
292 arr <- liftIO $ MA.newPinned n
293 foldFunc i rh snoc' arr rb
295 -- XXX We should write a read unfold for ring.
296 snoc' b a = liftIO $ MA.snocUnsafe b a
299 | i < n = RB.unsafeFoldRingM
300 | otherwise = RB.unsafeFoldRingFullM
302-------------------------------------------------------------------------------
304-------------------------------------------------------------------------------
306-------------------------------------------------------------------------------
308-------------------------------------------------------------------------------
310-- | Given a sorted array, perform a binary search to find the given element.
311-- Returns the index of the element if found.
314{-# INLINE binarySearch #-}
315binarySearch :: a -> Array a -> Maybe Int
316binarySearch = undefined
318-- find/findIndex etc can potentially be implemented more efficiently on arrays
319-- compared to streams by using SIMD instructions.
320-- We can also return a bit array instead.
322-- | Perform a linear search to find all the indices where a given element is
323-- present in an array.
326findIndicesOf :: (a -> Bool) -> Unfold Identity (Array a) Int
327findIndicesOf = undefined
330findIndexOf :: (a -> Bool) -> Array a -> Maybe Int
331findIndexOf p = Unfold.fold Fold.one . Stream.unfold (findIndicesOf p)
333find :: (a -> Bool) -> Array a -> Bool
334find = Unfold.fold Fold.null . Stream.unfold (findIndicesOf p)
337-------------------------------------------------------------------------------
339-------------------------------------------------------------------------------
341-- XXX We can potentially use SIMD instructions on arrays to fold faster.
343-------------------------------------------------------------------------------
345-------------------------------------------------------------------------------
347-- | /O(1)/ Slice an array in constant time.
349-- Caution: The bounds of the slice are not checked.
354{-# INLINE getSliceUnsafe #-}
357 => Int -- ^ starting index
358 -> Int -- ^ length of the slice
361getSliceUnsafe index len (Array contents start e) =
362 let size = SIZE_OF(a)
363 start1 = start + (index * size)
364 end1 = start1 + (len * size)
365 in assert (end1 <= e) (Array contents start1 end1)
367-- | Split the array into a stream of slices using a predicate. The element
368-- matching the predicate is dropped.
371{-# INLINE splitOn #-}
372splitOn :: (Monad m, Unbox a) =>
373 (a -> Bool) -> Array a -> Stream m (Array a)
374splitOn predicate arr =
376 $ fmap (\(i, len) -> getSliceUnsafe i len arr)
377 $ D.sliceOnSuffix predicate (A.toStreamD arr)
379{-# INLINE genSlicesFromLen #-}
380genSlicesFromLen :: forall m a. (Monad m, Unbox a)
381 => Int -- ^ from index
382 -> Int -- ^ length of the slice
383 -> Unfold m (Array a) (Int, Int)
384genSlicesFromLen from len =
385 Unfold.lmap A.unsafeThaw (MA.genSlicesFromLen from len)
387-- | Generate a stream of slices of specified length from an array, starting
388-- from the supplied array index. The last slice may be shorter than the
392{-# INLINE getSlicesFromLen #-}
393getSlicesFromLen :: forall m a. (Monad m, Unbox a)
394 => Int -- ^ from index
395 -> Int -- ^ length of the slice
396 -> Unfold m (Array a) (Array a)
397getSlicesFromLen from len =
399 $ Unfold.lmap A.unsafeThaw (MA.getSlicesFromLen from len)
401-------------------------------------------------------------------------------
402-- Random reads and writes
403-------------------------------------------------------------------------------
405-- XXX Change this to a partial function instead of a Maybe type? And use
406-- MA.getIndex instead.
408-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
410{-# INLINE getIndex #-}
411getIndex :: forall a. Unbox a => Int -> Array a -> Maybe a
415 let elemPtr = INDEX_OF(arrStart arr, i, a)
416 if i >= 0 && INDEX_VALID(elemPtr, arrEnd arr, a)
417 then Just <$> peekWith (arrContents arr) elemPtr
420-- | Given a stream of array indices, read the elements on those indices from
421-- the supplied Array. An exception is thrown if an index is out of bounds.
423-- This is the most general operation. We can implement other operations in
428-- let u = lmap (\arr -> (0, length arr - 1)) Unfold.enumerateFromTo
429-- in Unfold.lmap f (getIndices arr)
432-- let i = length arr - 1
433-- in Unfold.lmap f (getIndicesFromThenTo i (i - 1) 0)
437{-# INLINE getIndices #-}
438getIndices :: (Monad m, Unbox a) => Stream m Int -> Unfold m (Array a) a
440 let unf = MA.getIndicesD (return . unsafeInlineIO) $ D.fromStreamK $ Stream.toStreamK m
441 in Unfold.lmap A.unsafeThaw unf
443-- | Unfolds @(from, then, to, array)@ generating a finite stream whose first
444-- element is the array value from the index @from@ and the successive elements
445-- are from the indices in increments of @then@ up to @to@. Index enumeration
446-- can occur downwards or upwards depending on whether @then@ comes before or
450-- getIndicesFromThenTo =
451-- let f (from, next, to, arr) =
452-- (Stream.enumerateFromThenTo from next to, arr)
453-- in Unfold.lmap f getIndices
457{-# INLINE getIndicesFromThenTo #-}
458getIndicesFromThenTo :: Unfold m (Int, Int, Int, Array a) a
459getIndicesFromThenTo = undefined
461-------------------------------------------------------------------------------
462-- Transform via stream operations
463-------------------------------------------------------------------------------
465-- for non-length changing operations we can use the original length for
466-- allocation. If we can predict the length then we can use the prediction for
467-- new allocation. Otherwise we can use a hint and adjust dynamically.
470-- | Transform an array into another array using a pipe transformation
473{-# INLINE runPipe #-}
474runPipe :: (MonadIO m, Unbox a, Unbox b)
475 => Pipe m a b -> Array a -> m (Array b)
476runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
479-- XXX For transformations that cannot change the number of elements e.g. "map"
480-- we can use a predetermined array length.
482-- | Transform an array into another array using a stream transformation
486{-# INLINE streamTransform #-}
487streamTransform :: forall m a b. (MonadIO m, Unbox a, Unbox b)
488 => (Stream m a -> Stream m b) -> Array a -> m (Array b)
489streamTransform f arr =
490 P.fold (A.writeWith (length arr)) $ Stream.toStreamK $ f (A.read arr)
492-------------------------------------------------------------------------------
494-------------------------------------------------------------------------------
496-- | Cast an array having elements of type @a@ into an array having elements of
497-- type @b@. The array size must be a multiple of the size of type @b@
498-- otherwise accessing the last element of the array may result into a crash or
508castUnsafe (Array contents start end) =
509 Array (castContents contents) start end
511-- | Cast an @Array a@ into an @Array Word8@.
514asBytes :: Array a -> Array Word8
517-- | Cast an array having elements of type @a@ into an array having elements of
518-- type @b@. The length of the array should be a multiple of the size of the
519-- target element otherwise 'Nothing' is returned.
522cast :: forall a b. (Unbox b) => Array a -> Maybe (Array b)
524 let len = A.byteLength arr
525 r = len `mod` SIZE_OF(b)
528 else Just $ castUnsafe arr
530-- | Convert an array of any type into a null terminated CString Ptr.
534-- /O(n) Time: (creates a copy of the array)/
538asCStringUnsafe :: Array a -> (CString -> IO b) -> IO b
539asCStringUnsafe arr act = do
540 -- XXX Ensure a pinned allocation here.
541 let arr1 = asBytes arr <> A.fromList [0]
542 asPtrUnsafe arr1 $ \ptr -> act (castPtr ptr)
544-------------------------------------------------------------------------------
546-------------------------------------------------------------------------------
548-- XXX We can directly use toStreamD and D.fold here.
550-- | Fold an array using a 'Fold'.
554fold :: forall m a b. (Monad m, Unbox a) => Fold m a b -> Array a -> m b
555fold f arr = P.fold f (Stream.toStreamK (A.read arr))
557-- | Fold an array using a stream fold operation.
560{-# INLINE streamFold #-}
561streamFold :: (Monad m, Unbox a) => (Stream m a -> m b) -> Array a -> m b
562streamFold f arr = f (A.read 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