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
117 -- , flattenArraysRev
138 -- * Immutable Transformations
147import Control.Monad (when)
148import Control.Monad.IO.Class (MonadIO(..))
149import Data.Functor.Identity (Identity)
150import Data.Word (Word8)
151import Foreign.ForeignPtr (withForeignPtr)
152import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
153import Foreign.Ptr (minusPtr, plusPtr, castPtr)
154import Foreign.Storable (Storable(..))
155import Prelude hiding (length, null, last, map, (!!), read)
157import Streamly.Mem.Array.Types (Array(..), length)
158import Streamly.Streams.Serial (SerialT)
159import Streamly.Streams.StreamK.Type (IsStream)
160import Streamly.Fold.Types (Fold(..))
162import qualified Streamly.Fold as FL
163import qualified Streamly.Mem.Array.Types as A
164import qualified Streamly.Prelude as S
165import qualified Streamly.Streams.StreamD as D
166import qualified Streamly.Streams.Prelude as P
168-------------------------------------------------------------------------------
170-------------------------------------------------------------------------------
173-- | Create a new uninitialized array of given length.
176newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
177newArray len = undefined
180-- | Create an 'Array' from the first N elements of a stream. The array is
181-- allocated to size N, if the stream terminates before N elements then the
182-- array may hold less than N elements.
186writeN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
188 if n < 0 then error "writeN: negative write count specified" else return ()
189 A.fromStreamDN n $ D.toStreamD m
191-------------------------------------------------------------------------------
193-------------------------------------------------------------------------------
195-- | Convert an 'Array' into a stream in reverse order.
198{-# INLINE_EARLY readRev #-}
199readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
200readRev = D.fromStreamD . A.toStreamDRev
201-- XXX add fallback to StreamK rule
202-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
203-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
206_null :: Storable a => Array a -> Bool
207_null arr = length arr == 0
210_last :: (MonadIO m, Storable a) => Array a -> m (Maybe a)
211_last arr = readIndex arr (length arr - 1)
213-------------------------------------------------------------------------------
215-------------------------------------------------------------------------------
217-------------------------------------------------------------------------------
219-------------------------------------------------------------------------------
222-- | Perform a binary search in the array to find an element.
223bsearch :: a -> Array a -> Maybe Bool
226-- | Perform a binary search in the array to find an element index.
227{-# INLINE elemIndex #-}
228bsearchIndex :: a -> Array a -> Maybe Int
229bsearchIndex elem arr = undefined
231-- find/findIndex etc can potentially be implemented more efficiently on arrays
232-- compared to streams by using SIMD instructions.
234find :: (a -> Bool) -> Array a -> Bool
237findIndex :: (a -> Bool) -> Array a -> Maybe Int
240findIndices :: (a -> Bool) -> Array a -> Array Int
241findIndices = undefined
244-------------------------------------------------------------------------------
246-------------------------------------------------------------------------------
248-- XXX We can potentially use SIMD instructions on arrays to fold faster.
250-------------------------------------------------------------------------------
252-------------------------------------------------------------------------------
255slice :: Int -> Int -> Array a
256slice begin end arr = undefined
258splitAt :: Int -> Array a -> (Array a, Array a)
259splitAt i arr = undefined
261-- XXX This operation can be performed efficiently via streams.
262-- | Append two arrays together to create a single array.
263splice :: Array a -> Array a -> Array a
264splice arr1 arr2 = undefined
266-------------------------------------------------------------------------------
267-- In-place mutation APIs
268-------------------------------------------------------------------------------
270-- | Partition an array into two halves using a partitioning predicate. The
271-- first half retains values where the predicate is 'False' and the second half
272-- retains values where the predicate is 'True'.
273{-# INLINE partitionBy #-}
274partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
275partitionBy f arr = undefined
277-- | Shuffle corresponding elements from two arrays using a shuffle function.
278-- If the shuffle function returns 'False' then do nothing otherwise swap the
279-- elements. This can be used in a bottom up fold to shuffle or reorder the
281shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
282shuffleBy f arr1 arr2 = undefined
284-- XXX we can also make the folds partial by stopping at a certain level.
286-- | Perform a top down hierarchical recursive partitioning fold of items in
287-- the container using the given function as the partition function.
289-- This will perform a quick sort if the partition function is
290-- 'partitionBy (< pivot)'.
293{-# INLINABLE foldtWith #-}
294foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
295foldtWith level f = undefined
297-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
298-- indicates the level in the tree where the fold would stop.
300-- This will perform a random shuffle if the shuffle function is random.
301-- If we stop at level 0 and repeatedly apply the function then we can do a
303foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
304foldbWith level f = undefined
307-- XXX consider the bulk update/accumulation/permutation APIs from vector.
309-------------------------------------------------------------------------------
310-- Random reads and writes
311-------------------------------------------------------------------------------
313-- | /O(1)/ Lookup the element at the given index.
316{-# INLINE readIndex #-}
317readIndex :: (MonadIO m, Storable a) => Array a -> Int -> m (Maybe a)
319 if i < 0 || i > length arr - 1
321 else liftIO $ withForeignPtr (aStart arr) $ \p ->
322 fmap Just $ peekElemOff p i
325-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
326-- at index @i@ and reading up to @count@ elements in the forward direction
327-- ending at the index @i + count - 1@.
330{-# INLINE readSlice #-}
331readSlice :: (IsStream t, Monad m, Storable a)
332 => Array a -> Int -> Int -> t m a
333readSlice arr i len = undefined
335-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
336-- index @i@ and reading up to @count@ elements in the reverse direction ending
337-- at the index @i - count + 1@.
340{-# INLINE readSliceRev #-}
341readSliceRev :: (IsStream t, Monad m, Storable a)
342 => Array a -> Int -> Int -> t m a
343readSliceRev arr i len = undefined
346-- | /O(1)/ Write the given element at the given index in the array.
349{-# INLINE writeIndex #-}
350writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
351writeIndex arr i a = do
352 let maxIndex = length arr - 1
354 then error "writeIndex: negative array index"
356 then error $ "writeIndex: specified array index " ++ show i
357 ++ " is beyond the maximum index " ++ show maxIndex
359 liftIO $ withForeignPtr (aStart arr) $ \p ->
363-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
364-- starting at index @i@ and writing up to @count@ elements in the forward
365-- direction ending at the index @i + count - 1@.
368{-# INLINE writeSlice #-}
369writeSlice :: (IsStream t, Monad m, Storable a)
370 => Array a -> Int -> Int -> t m a -> m ()
371writeSlice arr i len s = undefined
373-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
374-- starting at index @i@ and writing up to @count@ elements in the reverse
375-- direction ending at the index @i - count + 1@.
378{-# INLINE writeSliceRev #-}
379writeSliceRev :: (IsStream t, Monad m, Storable a)
380 => Array a -> Int -> Int -> t m a -> m ()
381writeSliceRev arr i len s = undefined
384-------------------------------------------------------------------------------
386-------------------------------------------------------------------------------
388-- exponentially increasing sizes of the chunks upto the max limit.
389-- XXX this will be easier to implement with parsers/terminating folds
390-- With this we should be able to reduce the number of chunks/allocations.
391-- The reallocation/copy based toArray can also be implemented using this.
394{-# INLINE toArraysInRange #-}
395toArraysInRange :: (IsStream t, MonadIO m, Storable a)
396 => Int -> Int -> Fold m (Array a) b -> Fold m a b
397toArraysInRange low high (Fold step initial extract) =
400-- | Fold the input to a pure buffered stream (List) of arrays.
401{-# INLINE _toArraysOf #-}
402_toArraysOf :: (MonadIO m, Storable a)
403 => Int -> Fold m a (SerialT Identity (Array a))
404_toArraysOf n = FL.lchunksOf n (A.toArrayN n) FL.toStream
406-- XXX The realloc based implementation needs to make one extra copy if we use
407-- shrinkToFit. On the other hand, the stream of arrays implementation may
408-- buffer the array chunk pointers in memory but it does not have to shrink as
409-- we know the exact size in the end. However, memory copying does not seems to
410-- be as expensive as the allocations. Therefore, we need to reduce the number
411-- of allocations instead. Also, the size of allocations matters, right sizing
412-- an allocation even at the cost of copying sems to help. Should be measured
413-- on a big stream with heavy calls to toArray to see the effect.
415-- XXX check if GHC's memory allocator is efficient enough. We can try the C
416-- malloc to compare against.
418{-# INLINE bytesToCount #-}
419bytesToCount :: Storable a => a -> Int -> Int
421 let elemSize = sizeOf x
422 in n + elemSize - 1 `div` elemSize
424{-# INLINE_NORMAL toArrayMinChunk #-}
425toArrayMinChunk :: forall m a. (MonadIO m, Storable a)
426 => Int -> Fold m a (Array a)
427-- toArrayMinChunk n = FL.mapM spliceArrays $ toArraysOf n
428toArrayMinChunk elemCount = Fold step initial extract
432 insertElem (Array start end bound) x = do
434 return $ Array start (end `plusPtr` sizeOf (undefined :: a)) bound
437 when (elemCount < 0) $ error "toArrayMinChunk: elemCount is negative"
438 liftIO $ A.newArray elemCount
439 step arr@(Array start end bound) x | end == bound = do
440 let p = unsafeForeignPtrToPtr start
441 oldSize = end `minusPtr` p
442 newSize = max (oldSize * 2) 1
443 arr1 <- liftIO $ A.realloc newSize arr
445 step arr x = insertElem arr x
446 extract = liftIO . A.shrinkToFit
448-- | Fold the whole input to a single array.
450-- /Caution! Do not use this on infinite streams./
453{-# INLINE toArray #-}
454toArray :: forall m a. (MonadIO m, Storable a) => Fold m a (Array a)
455toArray = toArrayMinChunk (bytesToCount (undefined :: a) (A.mkChunkSize 1024))
457-- | Convert a stream of arrays into a stream of their elements.
460{-# INLINE flattenArrays #-}
461flattenArrays :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
462flattenArrays m = D.fromStreamD $ A.flattenArrays (D.toStreamD m)
464-- XXX should we have a reverseArrays API to reverse the stream of arrays
467-- | Convert a stream of arrays into a stream of their elements reversing the
468-- contents of each array before flattening.
471{-# INLINE _flattenArraysRev #-}
472_flattenArraysRev :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
473_flattenArraysRev m = D.fromStreamD $ A.flattenArraysRev (D.toStreamD m)
475-- XXX use an Array instead as separator? Or use a separate unlinesArraysBySeq
478-- | Flatten a stream of arrays appending the given element after each
482{-# INLINE unlinesArraysBy #-}
483unlinesArraysBy :: (MonadIO m, IsStream t, Storable a)
484 => a -> t m (Array a) -> t m a
485unlinesArraysBy x = D.fromStreamD . A.unlines x . D.toStreamD
487-- | Split a stream of arrays on a given separator byte, dropping the separator
488-- and coalescing all the arrays between two separators into a single array.
491{-# INLINE splitArraysOn #-}
493 :: (IsStream t, MonadIO m)
497splitArraysOn byte s = D.fromStreamD $ A.splitOn byte $ D.toStreamD s
499-- | Coalesce adajcent arrays in incoming stream to form bigger arrays of a
500-- maximum specified size.
503{-# INLINE packArraysChunksOf #-}
504packArraysChunksOf :: (MonadIO m, Storable a)
505 => Int -> SerialT m (Array a) -> SerialT m (Array a)
506packArraysChunksOf n xs =
507 D.fromStreamD $ A.packArraysChunksOf n (D.toStreamD xs)
510-- > arraysOf n = FL.groupsOf n (FL.toArrayN n)
512-- Groups the elements in an input stream into arrays of given size.
515{-# INLINE arraysOf #-}
516arraysOf :: (IsStream t, MonadIO m, Storable a)
517 => Int -> t m a -> t m (Array a)
519 D.fromStreamD $ A.fromStreamDArraysOf n (D.toStreamD str)
521-- XXX Both of these implementations of splicing seem to perform equally well.
522-- We need to perform benchmarks over a range of sizes though.
524-- CAUTION! length must more than equal to lengths of all the arrays in the
526{-# INLINE spliceArraysLenUnsafe #-}
527spliceArraysLenUnsafe :: (MonadIO m, Storable a)
528 => Int -> SerialT m (Array a) -> m (Array a)
529spliceArraysLenUnsafe len buffered = do
530 arr <- liftIO $ A.newArray len
531 end <- S.foldlM' writeArr (aEnd arr) buffered
532 return $ arr {aEnd = end}
536 writeArr dst Array{..} =
537 liftIO $ withForeignPtr aStart $ \src -> do
538 let count = aEnd `minusPtr` src
539 A.memcpy (castPtr dst) (castPtr src) count
540 return $ dst `plusPtr` count
542{-# INLINE _spliceArraysBuffered #-}
543_spliceArraysBuffered :: (MonadIO m, Storable a)
544 => SerialT m (Array a) -> m (Array a)
545_spliceArraysBuffered s = do
546 buffered <- P.foldr S.cons S.nil s
547 len <- S.sum (S.map length buffered)
548 spliceArraysLenUnsafe len s
550{-# INLINE spliceArraysRealloced #-}
551spliceArraysRealloced :: forall m a. (MonadIO m, Storable a)
552 => SerialT m (Array a) -> m (Array a)
553spliceArraysRealloced s = do
554 idst <- liftIO $ A.newArray (bytesToCount (undefined :: a)
557 arr <- S.foldlM' A.spliceWithDoubling idst s
558 liftIO $ A.shrinkToFit arr
560-- | Given a stream of arrays, splice them all together to generate a single
561-- array. The stream must be /finite/.
564{-# INLINE packArrays #-}
565packArrays :: (MonadIO m, Storable a) => SerialT m (Array a) -> m (Array a)
566packArrays = spliceArraysRealloced
567-- spliceArrays = _spliceArraysBuffered
569-- | Create an 'Array' from a stream. This is useful when we want to create a
570-- single array from a stream of unknown size. 'writeN' is at least twice
571-- as efficient when the size is already known.
573-- Note that if the input stream is too large memory allocation for the array
574-- may fail. When the stream size is not known, `arraysOf` followed by
575-- processing of indvidual arrays in the resulting stream should be preferred.
578write :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
579write = FL.foldl' toArray
580-- write m = A.fromStreamD $ D.toStreamD m
582-- XXX efficiently compare two streams of arrays. Two streams can have chunks
583-- of different sizes, we can handle that in the stream comparison abstraction.
584-- This could be useful e.g. to fast compare whether two files differ.
586-------------------------------------------------------------------------------
587-- Transform via stream operations
588-------------------------------------------------------------------------------
590-- for non-length changing operations we can use the original length for
591-- allocation. If we can predict the length then we can use the prediction for
592-- new allocation. Otherwise we can use a hint and adjust dynamically.
594-- | Transform an array into another array using a stream transformation
598{-# INLINE transformWith #-}
599transformWith :: (MonadIO m, Storable a, Storable b)
600 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
601transformWith f arr = FL.foldl' (toArrayMinChunk (length arr)) $ f (A.read arr)
603-- | Fold an array using a 'Fold'.
606{-# INLINE foldArray #-}
607foldArray :: (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
608foldArray f arr = FL.foldl' f (A.read arr)
610-- | Fold an array using a stream fold operation.
613{-# INLINE foldWith #-}
614foldWith :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
615foldWith 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