1{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
6{-# LANGUAGE ScopedTypeVariables #-}
11-- Module : Streamly.Mem.Array
12-- Copyright : (c) 2019 Harendra Kumar
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
19-- Arrays are the computing duals of streams. Streams are good at sequential
20-- access, immutable transformations of in-transit data whereas arrays are good
21-- at random access, in-place transformations of buffered data. Unlike streams
22-- which are potentially infinite, arrays are necessarily /finite/. Arrays can
23-- be used as an efficient interface between streams and external storage
24-- systems like memory, files and network. Streams and arrays complete each
25-- other to provide a general purpose computing system. The design of streamly
26-- as a general purpose computing framework is centered around these two
27-- fundamental aspects of computing and storage.
29-- Even though the implementation allows for in-place mutation, the current
30-- implementation of arrays is immutable. Arrays are of fixed size. The size of
31-- an array is fixed at creation and cannot be changed later without copying.
32-- Arrays are chunks of memory that hold a sequence of 'Storable' values of a
33-- given type. They are designed to store serializable data, they cannot store
34-- non-serializable data like functions, this is reflected by the 'Storable'
35-- constraint. For efficient buffering of data, arrays use pinned memory and
36-- therefore can hold arbitrary number of elements with a single movable
37-- pointer visible to GC, therefore, adding no pressure to GC. Moreover,
38-- pinned memory allows communication with foreign consumers and producers
39-- (e.g. file or network IO) without copying the data.
41-- By design, there are no transformation operations provided in this module,
42-- only stream conversion and IO routines are provided. An array is purely a
43-- data store, therefore, it is not a 'Functor'. Arrays can be operated upon
44-- /efficiently/ by converting them into a stream, applying the desired
45-- transformations on the stream and then converting it back to an array.
46-- 'Foldable' instance is not provided because the implementation would be much
47-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
48-- instances are deliberately not provided to avoid misuse; concatenating
49-- arrays using binary operations can be highly inefficient. Instead, use
50-- 'spliceArrays' to concatenate N arrays at once.
54-- * Arrays are finite and fixed in size
55-- * provide /O(1)/ access to elements
56-- * store only data and not functions
57-- * provide efficient IO interfacing
59-- 'ByteString' data type from the 'bytestring' package and the 'Text' data
60-- type from the 'text' package are just special cases of arrays. 'ByteString'
61-- is equivalent to @Array Word8@ and 'Text' is equivalent to a @utf16@ encoded
62-- @Array Word8@. All the 'bytestring' and 'text' operations can be performed
63-- on arrays with equivalent or better performance by converting them to and
66-- This module is designed to be imported qualified:
68-- > import qualified Streamly.Array as A
70-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
71-- single byte) are only as good as holding those elements in a Haskell list.
72-- However, small arrays can be compacted into large ones to reduce the
73-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
74-- if we use one array for each chunk. This is still significant to add
75-- pressure to GC. However, we can create arrays of arrays (trees) to scale to
76-- arbitrarily large amounts of memory but still using small chunks of
79module Streamly.Mem.Array
86 -- | When performance matters, the fastest way to generate an array is
87 -- 'writeN'. For regular use, 'IsList' and 'IsString' instances can be
88 -- used to conveniently construct arrays from literal values.
89 -- 'OverloadedLists' extension or 'fromList' can be used to construct an
90 -- array from a list literal. Similarly, 'OverloadedStrings' extension or
91 -- 'fromList' can be used to construct an array from a string literal.
108 -- 'GHC.Exts.toList' from "GHC.Exts" can be used to convert an array to a
115 -- , flattenArraysRev
131 -- * Immutable Transformations
140import Control.Monad (when)
141import Control.Monad.IO.Class (MonadIO(..))
142import Data.Functor.Identity (Identity)
143import Foreign.ForeignPtr (withForeignPtr)
144import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
145import Foreign.Ptr (minusPtr, plusPtr, castPtr)
146import Foreign.Storable (Storable(..))
147import Prelude hiding (length, null, last, map, (!!), read)
149import Streamly.Mem.Array.Types hiding (flattenArrays, newArray)
150import Streamly.Streams.Serial (SerialT)
151import Streamly.Streams.StreamK.Type (IsStream)
152import Streamly.Fold.Types (Fold(..))
154import qualified Streamly.Fold as FL
155import qualified Streamly.Mem.Array.Types as A
156import qualified Streamly.Prelude as S
157import qualified Streamly.Streams.StreamD as D
158import qualified Streamly.Streams.Prelude as P
160-------------------------------------------------------------------------------
162-------------------------------------------------------------------------------
165-- | Create a new uninitialized array of given length.
168newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
169newArray len = undefined
172-- | Create an 'Array' from the first N elements of a stream. The array is
173-- allocated to size N, if the stream terminates before N elements then the
174-- array may hold less than N elements.
178writeN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
180 if n < 0 then error "writeN: negative write count specified" else return ()
181 fromStreamDN n $ D.toStreamD m
183-------------------------------------------------------------------------------
185-------------------------------------------------------------------------------
187-- | Convert an 'Array' into a stream in reverse order.
190{-# INLINE_EARLY readRev #-}
191readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
192readRev = D.fromStreamD . toStreamDRev
193-- XXX add fallback to StreamK rule
194-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
195-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
198_null :: Storable a => Array a -> Bool
199_null arr = length arr == 0
202_last :: forall a. Storable a => Array a -> Maybe a
203_last arr = readIndex arr (length arr - 1)
205-------------------------------------------------------------------------------
207-------------------------------------------------------------------------------
209-------------------------------------------------------------------------------
211-------------------------------------------------------------------------------
214-- | Perform a binary search in the array to find an element.
215bsearch :: a -> Array a -> Maybe Bool
218-- | Perform a binary search in the array to find an element index.
219{-# INLINE elemIndex #-}
220bsearchIndex :: a -> Array a -> Maybe Int
221bsearchIndex elem arr = undefined
223-- find/findIndex etc can potentially be implemented more efficiently on arrays
224-- compared to streams by using SIMD instructions.
226find :: (a -> Bool) -> Array a -> Bool
229findIndex :: (a -> Bool) -> Array a -> Maybe Int
232findIndices :: (a -> Bool) -> Array a -> Array Int
233findIndices = undefined
236-------------------------------------------------------------------------------
238-------------------------------------------------------------------------------
240-- XXX We can potentially use SIMD instructions on arrays to fold faster.
242-------------------------------------------------------------------------------
244-------------------------------------------------------------------------------
247slice :: Int -> Int -> Array a
248slice begin end arr = undefined
250splitAt :: Int -> Array a -> (Array a, Array a)
251splitAt i arr = undefined
253-- XXX This operation can be performed efficiently via streams.
254-- | Append two arrays together to create a single array.
255splice :: Array a -> Array a -> Array a
256splice arr1 arr2 = undefined
258-------------------------------------------------------------------------------
259-- In-place mutation APIs
260-------------------------------------------------------------------------------
262-- | Partition an array into two halves using a partitioning predicate. The
263-- first half retains values where the predicate is 'False' and the second half
264-- retains values where the predicate is 'True'.
265{-# INLINE partitionBy #-}
266partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
267partitionBy f arr = undefined
269-- | Shuffle corresponding elements from two arrays using a shuffle function.
270-- If the shuffle function returns 'False' then do nothing otherwise swap the
271-- elements. This can be used in a bottom up fold to shuffle or reorder the
273shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
274shuffleBy f arr1 arr2 = undefined
276-- XXX we can also make the folds partial by stopping at a certain level.
278-- | Perform a top down hierarchical recursive partitioning fold of items in
279-- the container using the given function as the partition function.
281-- This will perform a quick sort if the partition function is
282-- 'partitionBy (< pivot)'.
285{-# INLINABLE foldtWith #-}
286foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
287foldtWith level f = undefined
289-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
290-- indicates the level in the tree where the fold would stop.
292-- This will perform a random shuffle if the shuffle function is random.
293-- If we stop at level 0 and repeatedly apply the function then we can do a
295foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
296foldbWith level f = undefined
299-- XXX consider the bulk update/accumulation/permutation APIs from vector.
301-------------------------------------------------------------------------------
302-- Random reads and writes
303-------------------------------------------------------------------------------
305-- | /O(1)/ Lookup the element at the given index.
308{-# INLINE readIndex #-}
309readIndex :: Storable a => Array a -> Int -> Maybe a
311 if i < 0 || i > length arr - 1
313 else Just $ unsafeIndex arr i
316-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
317-- at index @i@ and reading up to @count@ elements in the forward direction
318-- ending at the index @i + count - 1@.
321{-# INLINE readSlice #-}
322readSlice :: (IsStream t, Monad m, Storable a)
323 => Array a -> Int -> Int -> t m a
324readSlice arr i len = undefined
326-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
327-- index @i@ and reading up to @count@ elements in the reverse direction ending
328-- at the index @i - count + 1@.
331{-# INLINE readSliceRev #-}
332readSliceRev :: (IsStream t, Monad m, Storable a)
333 => Array a -> Int -> Int -> t m a
334readSliceRev arr i len = undefined
336-- | /O(1)/ Write the given element at the given index in the array.
339{-# INLINE writeIndex #-}
340writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
341writeIndex arr i a = undefined
343-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
344-- starting at index @i@ and writing up to @count@ elements in the forward
345-- direction ending at the index @i + count - 1@.
348{-# INLINE writeSlice #-}
349writeSlice :: (IsStream t, Monad m, Storable a)
350 => Array a -> Int -> Int -> t m a -> m ()
351writeSlice arr i len s = undefined
353-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
354-- starting at index @i@ and writing up to @count@ elements in the reverse
355-- direction ending at the index @i - count + 1@.
358{-# INLINE writeSliceRev #-}
359writeSliceRev :: (IsStream t, Monad m, Storable a)
360 => Array a -> Int -> Int -> t m a -> m ()
361writeSliceRev arr i len s = undefined
364-------------------------------------------------------------------------------
366-------------------------------------------------------------------------------
368-- exponentially increasing sizes of the chunks upto the max limit.
369-- XXX this will be easier to implement with parsers/terminating folds
370-- With this we should be able to reduce the number of chunks/allocations.
371-- The reallocation/copy based toArray can also be implemented using this.
374{-# INLINE toArraysInRange #-}
375toArraysInRange :: (IsStream t, MonadIO m, Storable a)
376 => Int -> Int -> Fold m (Array a) b -> Fold m a b
377toArraysInRange low high (Fold step initial extract) =
380-- | Fold the input to a pure buffered stream (List) of arrays.
381{-# INLINE _toArraysOf #-}
382_toArraysOf :: (MonadIO m, Storable a)
383 => Int -> Fold m a (SerialT Identity (Array a))
384_toArraysOf n = FL.lchunksOf n (toArrayN n) FL.toStream
386-- XXX The realloc based implementation needs to make one extra copy if we use
387-- shrinkToFit. On the other hand, the stream of arrays implementation may
388-- buffer the array chunk pointers in memory but it does not have to shrink as
389-- we know the exact size in the end. However, memory copying does not seems to
390-- be as expensive as the allocations. Therefore, we need to reduce the number
391-- of allocations instead. Also, the size of allocations matters, right sizing
392-- an allocation even at the cost of copying sems to help. Should be measured
393-- on a big stream with heavy calls to toArray to see the effect.
395-- XXX check if GHC's memory allocator is efficient enough. We can try the C
396-- malloc to compare against.
398{-# INLINE bytesToCount #-}
399bytesToCount :: Storable a => a -> Int -> Int
401 let elemSize = sizeOf x
402 in n + elemSize - 1 `div` elemSize
404{-# INLINE toArrayMinChunk #-}
405toArrayMinChunk :: forall m a. (MonadIO m, Storable a)
406 => Int -> Fold m a (Array a)
407-- toArrayMinChunk n = FL.mapM spliceArrays $ toArraysOf n
408toArrayMinChunk elemCount = Fold step initial extract
412 insertElem (Array start end bound) x = do
414 return $ Array start (end `plusPtr` sizeOf (undefined :: a)) bound
417 when (elemCount < 0) $ error "toArrayMinChunk: elemCount is negative"
418 liftIO $ A.newArray elemCount
419 step arr@(Array _ end bound) x | end == bound = do
420 arr1 <- liftIO $ reallocDouble 1 arr
422 step arr x = insertElem arr x
423 extract = liftIO . shrinkToFit
425-- | Fold the whole input to a single array.
427-- /Caution! Do not use this on infinite streams./
430{-# INLINE toArray #-}
431toArray :: forall m a. (MonadIO m, Storable a) => Fold m a (Array a)
432toArray = toArrayMinChunk (bytesToCount (undefined :: a) (mkChunkSize 1024))
434-- | Convert a stream of arrays into a stream of their elements.
437{-# INLINE flattenArrays #-}
438flattenArrays :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
439flattenArrays m = D.fromStreamD $ A.flattenArrays (D.toStreamD m)
441-- XXX should we have a reverseArrays API to reverse the stream of arrays
444-- | Convert a stream of arrays into a stream of their elements reversing the
445-- contents of each array before flattening.
448{-# INLINE _flattenArraysRev #-}
449_flattenArraysRev :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
450_flattenArraysRev m = D.fromStreamD $ A.flattenArraysRev (D.toStreamD m)
453-- > arraysOf n = FL.groupsOf n (FL.toArrayN n)
455-- Groups the elements in an input stream into arrays of given size.
458{-# INLINE arraysOf #-}
459arraysOf :: (IsStream t, MonadIO m, Storable a)
460 => Int -> t m a -> t m (Array a)
462 D.fromStreamD $ fromStreamDArraysOf n (D.toStreamD str)
464-- XXX Both of these implementations of splicing seem to perform equally well.
465-- We need to perform benchmarks over a range of sizes though.
467{-# INLINE _spliceArraysRealloced #-}
468_spliceArraysRealloced :: (MonadIO m, Storable a)
469 => SerialT m (Array a) -> m (Array a)
470_spliceArraysRealloced s = do
471 buffered <- P.foldr S.cons S.nil s
472 len <- S.sum (S.map length buffered)
474 arr <- liftIO $ A.newArray len
475 end <- S.foldlM' writeArr (aEnd arr) buffered
476 return $ arr {aEnd = end}
480 writeArr dst Array{..} =
481 liftIO $ withForeignPtr aStart $ \src -> do
482 let len = aEnd `minusPtr` src
483 memcpy (castPtr dst) (castPtr src) len
484 return $ dst `plusPtr` len
486{-# INLINE spliceArraysBuffered #-}
487spliceArraysBuffered :: forall m a. (MonadIO m, Storable a)
488 => SerialT m (Array a) -> m (Array a)
489spliceArraysBuffered s = do
490 idst <- liftIO $ A.newArray (bytesToCount (undefined :: a)
492 arr <- S.foldlM' appendArr idst s
493 liftIO $ shrinkToFit arr
497 appendArr dst@(Array _ end bound) src = liftIO $ do
498 let srcLen = aEnd src `minusPtr` unsafeForeignPtrToPtr (aStart src)
500 if end `plusPtr` srcLen >= bound
501 then reallocDouble srcLen dst
504 withForeignPtr (aStart dst1) $ \_ -> do
505 withForeignPtr (aStart src) $ \psrc -> do
507 memcpy (castPtr pdst) (castPtr psrc) srcLen
508 return $ dst1 { aEnd = pdst `plusPtr` srcLen }
510-- | Given a stream of arrays, splice them all together to generate a single
511-- array. The stream must be /finite/.
514{-# INLINE spliceArrays #-}
515spliceArrays :: (MonadIO m, Storable a) => SerialT m (Array a) -> m (Array a)
516spliceArrays = spliceArraysBuffered
517-- spliceArrays = _spliceArraysRealloced
519-- | Create an 'Array' from a stream. This is useful when we want to create a
520-- single array from a stream of unknown size. 'writeN' is at least twice
521-- as efficient when the size is already known.
523-- Note that if the input stream is too large memory allocation for the array
524-- may fail. When the stream size is not known, `arraysOf` followed by
525-- processing of indvidual arrays in the resulting stream should be preferred.
528write :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
529write = FL.foldl' toArray
530-- write m = A.fromStreamD $ D.toStreamD m
532-- XXX efficiently compare two streams of arrays. Two streams can have chunks
533-- of different sizes, we can handle that in the stream comparison abstraction.
534-- This could be useful e.g. to fast compare whether two files differ.
536-------------------------------------------------------------------------------
537-- Transform via stream operations
538-------------------------------------------------------------------------------
540-- for non-length changing operations we can use the original length for
541-- allocation. If we can predict the length then we can use the prediction for
542-- new allocation. Otherwise we can use a hint and adjust dynamically.
544-- | Transform an array into another array using a stream transformation
548{-# INLINE transformWith #-}
549transformWith :: (MonadIO m, Storable a, Storable b)
550 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
551transformWith f arr = FL.foldl' (toArrayMinChunk (length arr)) $ f (read arr)
553-- | Fold an array using a 'Fold'.
556{-# INLINE foldArray #-}
557foldArray :: (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
558foldArray f arr = FL.foldl' f (read arr)
560-- | Fold an array using a stream fold operation.
563{-# INLINE foldWith #-}
564foldWith :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
565foldWith f arr = f (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