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 and immutable transformations of in-transit data whereas arrays are
21-- good at random access and in-place transformations of buffered data. Unlike
22-- streams which are potentially infinite, arrays are necessarily /finite/.
23-- Arrays can be used as an efficient interface between streams and external
24-- storage systems like memory, files and network. Streams and arrays complete
25-- each other to provide a general purpose computing system. The design of
26-- streamly as a general purpose computing framework is centered around these
27-- two 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
131 -- * Immutable Transformations
140import Control.Monad (when)
141import Control.Monad.IO.Class (MonadIO(..))
142-- import Data.Functor.Identity (Identity)
143import Foreign.ForeignPtr (withForeignPtr)
144import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
145import Foreign.Ptr (minusPtr, plusPtr)
146import Foreign.Storable (Storable(..))
147import Prelude hiding (length, null, last, map, (!!), read)
149import Streamly.Mem.Array.Types (Array(..), length)
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.Streams.StreamD as D
158-------------------------------------------------------------------------------
160-------------------------------------------------------------------------------
163-- | Create a new uninitialized array of given length.
166newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
167newArray len = undefined
170-- | Create an 'Array' from the first N elements of a stream. The array is
171-- allocated to size N, if the stream terminates before N elements then the
172-- array may hold less than N elements.
176writeN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
178 if n < 0 then error "writeN: negative write count specified" else return ()
179 A.fromStreamDN n $ D.toStreamD m
181-------------------------------------------------------------------------------
183-------------------------------------------------------------------------------
185-- | Convert an 'Array' into a stream in reverse order.
188{-# INLINE_EARLY readRev #-}
189readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
190readRev = D.fromStreamD . A.toStreamDRev
191-- XXX add fallback to StreamK rule
192-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
193-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
196_null :: Storable a => Array a -> Bool
197_null arr = length arr == 0
200_last :: (MonadIO m, Storable a) => Array a -> m (Maybe a)
201_last arr = readIndex arr (length arr - 1)
203-------------------------------------------------------------------------------
205-------------------------------------------------------------------------------
207-------------------------------------------------------------------------------
209-------------------------------------------------------------------------------
212-- | Perform a binary search in the array to find an element.
213bsearch :: a -> Array a -> Maybe Bool
216-- | Perform a binary search in the array to find an element index.
217{-# INLINE elemIndex #-}
218bsearchIndex :: a -> Array a -> Maybe Int
219bsearchIndex elem arr = undefined
221-- find/findIndex etc can potentially be implemented more efficiently on arrays
222-- compared to streams by using SIMD instructions.
224find :: (a -> Bool) -> Array a -> Bool
227findIndex :: (a -> Bool) -> Array a -> Maybe Int
230findIndices :: (a -> Bool) -> Array a -> Array Int
231findIndices = undefined
234-------------------------------------------------------------------------------
236-------------------------------------------------------------------------------
238-- XXX We can potentially use SIMD instructions on arrays to fold faster.
240-------------------------------------------------------------------------------
242-------------------------------------------------------------------------------
245slice :: Int -> Int -> Array a
246slice begin end arr = undefined
248splitAt :: Int -> Array a -> (Array a, Array a)
249splitAt i arr = undefined
251-- XXX This operation can be performed efficiently via streams.
252-- | Append two arrays together to create a single array.
253splice :: Array a -> Array a -> Array a
254splice arr1 arr2 = undefined
256-------------------------------------------------------------------------------
257-- In-place mutation APIs
258-------------------------------------------------------------------------------
260-- | Partition an array into two halves using a partitioning predicate. The
261-- first half retains values where the predicate is 'False' and the second half
262-- retains values where the predicate is 'True'.
263{-# INLINE partitionBy #-}
264partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
265partitionBy f arr = undefined
267-- | Shuffle corresponding elements from two arrays using a shuffle function.
268-- If the shuffle function returns 'False' then do nothing otherwise swap the
269-- elements. This can be used in a bottom up fold to shuffle or reorder the
271shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
272shuffleBy f arr1 arr2 = undefined
274-- XXX we can also make the folds partial by stopping at a certain level.
276-- | Perform a top down hierarchical recursive partitioning fold of items in
277-- the container using the given function as the partition function.
279-- This will perform a quick sort if the partition function is
280-- 'partitionBy (< pivot)'.
283{-# INLINABLE foldtWith #-}
284foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
285foldtWith level f = undefined
287-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
288-- indicates the level in the tree where the fold would stop.
290-- This will perform a random shuffle if the shuffle function is random.
291-- If we stop at level 0 and repeatedly apply the function then we can do a
293foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
294foldbWith level f = undefined
297-- XXX consider the bulk update/accumulation/permutation APIs from vector.
299-------------------------------------------------------------------------------
300-- Random reads and writes
301-------------------------------------------------------------------------------
303-- | /O(1)/ Lookup the element at the given index.
306{-# INLINE readIndex #-}
307readIndex :: (MonadIO m, Storable a) => Array a -> Int -> m (Maybe a)
309 if i < 0 || i > length arr - 1
311 else liftIO $ withForeignPtr (aStart arr) $ \p ->
312 fmap Just $ peekElemOff p i
315-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
316-- at index @i@ and reading up to @count@ elements in the forward direction
317-- ending at the index @i + count - 1@.
320{-# INLINE readSlice #-}
321readSlice :: (IsStream t, Monad m, Storable a)
322 => Array a -> Int -> Int -> t m a
323readSlice arr i len = undefined
325-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
326-- index @i@ and reading up to @count@ elements in the reverse direction ending
327-- at the index @i - count + 1@.
330{-# INLINE readSliceRev #-}
331readSliceRev :: (IsStream t, Monad m, Storable a)
332 => Array a -> Int -> Int -> t m a
333readSliceRev arr i len = undefined
336-- | /O(1)/ Write the given element at the given index in the array.
337-- Performs in-place mutation of the array.
340{-# INLINE _writeIndex #-}
341_writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
342_writeIndex arr i a = do
343 let maxIndex = length arr - 1
345 then error "writeIndex: negative array index"
347 then error $ "writeIndex: specified array index " ++ show i
348 ++ " is beyond the maximum index " ++ show maxIndex
350 liftIO $ withForeignPtr (aStart arr) $ \p ->
354-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
355-- starting at index @i@ and writing up to @count@ elements in the forward
356-- direction ending at the index @i + count - 1@.
359{-# INLINE writeSlice #-}
360writeSlice :: (IsStream t, Monad m, Storable a)
361 => Array a -> Int -> Int -> t m a -> m ()
362writeSlice arr i len s = undefined
364-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
365-- starting at index @i@ and writing up to @count@ elements in the reverse
366-- direction ending at the index @i - count + 1@.
369{-# INLINE writeSliceRev #-}
370writeSliceRev :: (IsStream t, Monad m, Storable a)
371 => Array a -> Int -> Int -> t m a -> m ()
372writeSliceRev arr i len s = undefined
375-------------------------------------------------------------------------------
377-------------------------------------------------------------------------------
379-- exponentially increasing sizes of the chunks upto the max limit.
380-- XXX this will be easier to implement with parsers/terminating folds
381-- With this we should be able to reduce the number of chunks/allocations.
382-- The reallocation/copy based toArray can also be implemented using this.
385{-# INLINE toArraysInRange #-}
386toArraysInRange :: (IsStream t, MonadIO m, Storable a)
387 => Int -> Int -> Fold m (Array a) b -> Fold m a b
388toArraysInRange low high (Fold step initial extract) =
392-- | Fold the input to a pure buffered stream (List) of arrays.
393{-# INLINE _toArraysOf #-}
394_toArraysOf :: (MonadIO m, Storable a)
395 => Int -> Fold m a (SerialT Identity (Array a))
396_toArraysOf n = FL.lchunksOf n (A.toArrayN n) FL.toStream
399-- XXX The realloc based implementation needs to make one extra copy if we use
400-- shrinkToFit. On the other hand, the stream of arrays implementation may
401-- buffer the array chunk pointers in memory but it does not have to shrink as
402-- we know the exact size in the end. However, memory copying does not seems to
403-- be as expensive as the allocations. Therefore, we need to reduce the number
404-- of allocations instead. Also, the size of allocations matters, right sizing
405-- an allocation even at the cost of copying sems to help. Should be measured
406-- on a big stream with heavy calls to toArray to see the effect.
408-- XXX check if GHC's memory allocator is efficient enough. We can try the C
409-- malloc to compare against.
411{-# INLINE_NORMAL toArrayMinChunk #-}
412toArrayMinChunk :: forall m a. (MonadIO m, Storable a)
413 => Int -> Fold m a (Array a)
414-- toArrayMinChunk n = FL.mapM spliceArrays $ toArraysOf n
415toArrayMinChunk elemCount = Fold step initial extract
419 insertElem (Array start end bound) x = do
421 return $ Array start (end `plusPtr` sizeOf (undefined :: a)) bound
424 when (elemCount < 0) $ error "toArrayMinChunk: elemCount is negative"
425 liftIO $ A.newArray elemCount
426 step arr@(Array start end bound) x | end == bound = do
427 let p = unsafeForeignPtrToPtr start
428 oldSize = end `minusPtr` p
429 newSize = max (oldSize * 2) 1
430 arr1 <- liftIO $ A.realloc newSize arr
432 step arr x = insertElem arr x
433 extract = liftIO . A.shrinkToFit
435-- | Fold the whole input to a single array.
437-- /Caution! Do not use this on infinite streams./
440{-# INLINE toArray #-}
441toArray :: forall m a. (MonadIO m, Storable a) => Fold m a (Array a)
443 toArrayMinChunk (A.bytesToCount (undefined :: a) (A.mkChunkSize 1024))
445-- | Create an 'Array' from a stream. This is useful when we want to create a
446-- single array from a stream of unknown size. 'writeN' is at least twice
447-- as efficient when the size is already known.
449-- Note that if the input stream is too large memory allocation for the array
450-- may fail. When the stream size is not known, `arraysOf` followed by
451-- processing of indvidual arrays in the resulting stream should be preferred.
454write :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
455write = FL.foldl' toArray
456-- write m = A.fromStreamD $ D.toStreamD m
458-- XXX efficiently compare two streams of arrays. Two streams can have chunks
459-- of different sizes, we can handle that in the stream comparison abstraction.
460-- This could be useful e.g. to fast compare whether two files differ.
462-------------------------------------------------------------------------------
463-- Transform via stream operations
464-------------------------------------------------------------------------------
466-- for non-length changing operations we can use the original length for
467-- allocation. If we can predict the length then we can use the prediction for
468-- new allocation. Otherwise we can use a hint and adjust dynamically.
470-- | Transform an array into another array using a stream transformation
474{-# INLINE transformWith #-}
475transformWith :: (MonadIO m, Storable a, Storable b)
476 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
477transformWith f arr = FL.foldl' (toArrayMinChunk (length arr)) $ f (A.read arr)
479-- | Fold an array using a 'Fold'.
482{-# INLINE foldArray #-}
483foldArray :: (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
484foldArray f arr = FL.foldl' f (A.read arr)
486-- | Fold an array using a stream fold operation.
489{-# INLINE foldWith #-}
490foldWith :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
491foldWith 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