1{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
6{-# LANGUAGE ScopedTypeVariables #-}
11-- Module : Streamly.Memory.Array
12-- Copyright : (c) 2019 Harendra Kumar
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
19-- This module provides immutable arrays suitable for storage and random
20-- access. Once created an array cannot be mutated without copying. Arrays in
21-- this module are chunks of memory that hold a sequence of 'Storable' values
22-- of a given type. They are designed to store serializable data, they cannot
23-- store non-serializable data like functions, this is reflected by the
24-- 'Storable' constraint. For efficient buffering of data, arrays use pinned
25-- memory and therefore can hold arbitrary number of elements with a single
26-- movable pointer visible to GC, therefore, adding no pressure to GC.
27-- Moreover, pinned memory allows communication with foreign consumers and
28-- producers (e.g. file or network IO) without copying the data.
30-- By design, there are no array transformation operations provided in this
31-- module, only conversion to and from stream is provided. Arrays can be
32-- operated upon /efficiently/ by converting them into a stream, applying the
33-- desired stream transformations from "Streamly.Prelude" and then converting
34-- it back to an array.
36-- This module is designed to be imported qualified:
38-- > import qualified Streamly.Array as A
42-- Arrays are finite and fixed in size
43-- provide /O(1)/ access to elements
44-- store only data and not functions
45-- provide efficient IO interfacing
47-- 'Foldable' instance is not provided because the implementation would be much
48-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
49-- instances are deliberately not provided to avoid misuse; concatenating
50-- arrays using binary operations can be highly inefficient. Instead, use
51-- 'Streamly.Memory.Array.Stream.toArray' to concatenate N arrays at once.
53-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
54-- single byte) are only as good as holding those elements in a Haskell list.
55-- However, small arrays can be compacted into large ones to reduce the
56-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
57-- if we use one array for each chunk. This is still significant to add
58-- pressure to GC. However, we can create arrays of arrays (trees) to scale to
59-- arbitrarily large amounts of memory but still using small chunks of
62module Streamly.Memory.Array
70 -- | When performance matters, the fastest way to generate an array is
71 -- 'writeN'. For regular use, 'IsList' and 'IsString' instances can be
72 -- used to conveniently construct arrays from literal values.
73 -- 'OverloadedLists' extension or 'fromList' can be used to construct an
74 -- array from a list literal. Similarly, 'OverloadedStrings' extension or
75 -- 'fromList' can be used to construct an array from a string literal.
83 , A.writeN -- drop new
84 , A.write -- full buffer
85 -- , writeLastN -- drop old (ring buffer)
92 -- 'GHC.Exts.toList' from "GHC.Exts" can be used to convert an array to a
116 -- * Immutable Transformations
126import Control.Monad.IO.Class (MonadIO(..))
127-- import Data.Functor.Identity (Identity)
128import Foreign.ForeignPtr (withForeignPtr)
129import Foreign.Storable (Storable(..))
130import Prelude hiding (length, null, last, map, (!!), read, concat)
132import Streamly.Internal.Memory.Array.Types (Array(..), length)
133import Streamly.Streams.Serial (SerialT)
134import Streamly.Streams.StreamK.Type (IsStream)
135import Streamly.Internal.Data.Fold.Types (Fold(..))
137import qualified Streamly.Internal.Memory.Array.Types as A
138import qualified Streamly.Streams.Prelude as P
139import qualified Streamly.Streams.Serial as Serial
140import qualified Streamly.Streams.StreamD as D
142-------------------------------------------------------------------------------
144-------------------------------------------------------------------------------
147-- | Create a new uninitialized array of given length.
150newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
151newArray len = undefined
154-- | Create an 'Array' from the first N elements of a stream. The array is
155-- allocated to size N, if the stream terminates before N elements then the
156-- array may hold less than N elements.
159{-# INLINE _writeNS #-}
160_writeNS :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
162 if n < 0 then error "writeN: negative write count specified" else return ()
163 A.fromStreamDN n $ D.toStreamD m
165-- | Create an 'Array' from a stream. This is useful when we want to create a
166-- single array from a stream of unknown size. 'writeN' is at least twice
167-- as efficient when the size is already known.
169-- Note that if the input stream is too large memory allocation for the array
170-- may fail. When the stream size is not known, `arraysOf` followed by
171-- processing of indvidual arrays in the resulting stream should be preferred.
173{-# INLINE _writeS #-}
174_writeS :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
175_writeS = P.runFold A.write
176-- write m = A.fromStreamD $ D.toStreamD m
178-------------------------------------------------------------------------------
180-------------------------------------------------------------------------------
182-- | Convert an 'Array' into a stream in reverse order.
185{-# INLINE_EARLY readRev #-}
186readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
187readRev = D.fromStreamD . A.toStreamDRev
188-- XXX add fallback to StreamK rule
189-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
190-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
193_null :: Storable a => Array a -> Bool
194_null arr = length arr == 0
197_last :: Storable a => Array a -> Maybe a
198_last arr = readIndex arr (length arr - 1)
200-------------------------------------------------------------------------------
202-------------------------------------------------------------------------------
204-------------------------------------------------------------------------------
206-------------------------------------------------------------------------------
209-- | Perform a binary search in the array to find an element.
210bsearch :: a -> Array a -> Maybe Bool
213-- | Perform a binary search in the array to find an element index.
214{-# INLINE elemIndex #-}
215bsearchIndex :: a -> Array a -> Maybe Int
216bsearchIndex elem arr = undefined
218-- find/findIndex etc can potentially be implemented more efficiently on arrays
219-- compared to streams by using SIMD instructions.
221find :: (a -> Bool) -> Array a -> Bool
224findIndex :: (a -> Bool) -> Array a -> Maybe Int
227findIndices :: (a -> Bool) -> Array a -> Array Int
228findIndices = undefined
231-------------------------------------------------------------------------------
233-------------------------------------------------------------------------------
235-- XXX We can potentially use SIMD instructions on arrays to fold faster.
237-------------------------------------------------------------------------------
239-------------------------------------------------------------------------------
242slice :: Int -> Int -> Array a
243slice begin end arr = undefined
245splitAt :: Int -> Array a -> (Array a, Array a)
246splitAt i arr = undefined
248-- XXX This operation can be performed efficiently via streams.
249-- | Append two arrays together to create a single array.
250splice :: Array a -> Array a -> Array a
251splice arr1 arr2 = undefined
253-------------------------------------------------------------------------------
254-- In-place mutation APIs
255-------------------------------------------------------------------------------
257-- | Partition an array into two halves using a partitioning predicate. The
258-- first half retains values where the predicate is 'False' and the second half
259-- retains values where the predicate is 'True'.
260{-# INLINE partitionBy #-}
261partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
262partitionBy f arr = undefined
264-- | Shuffle corresponding elements from two arrays using a shuffle function.
265-- If the shuffle function returns 'False' then do nothing otherwise swap the
266-- elements. This can be used in a bottom up fold to shuffle or reorder the
268shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
269shuffleBy f arr1 arr2 = undefined
271-- XXX we can also make the folds partial by stopping at a certain level.
273-- | Perform a top down hierarchical recursive partitioning fold of items in
274-- the container using the given function as the partition function.
276-- This will perform a quick sort if the partition function is
277-- 'partitionBy (< pivot)'.
280{-# INLINABLE foldtWith #-}
281foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
282foldtWith level f = undefined
284-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
285-- indicates the level in the tree where the fold would stop.
287-- This will perform a random shuffle if the shuffle function is random.
288-- If we stop at level 0 and repeatedly apply the function then we can do a
290foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
291foldbWith level f = undefined
294-- XXX consider the bulk update/accumulation/permutation APIs from vector.
296-------------------------------------------------------------------------------
297-- Random reads and writes
298-------------------------------------------------------------------------------
300-- | /O(1)/ Lookup the element at the given index, starting from 0.
303{-# INLINE readIndex #-}
304readIndex :: Storable a => Array a -> Int -> Maybe a
306 if i < 0 || i > length arr - 1
308 else A.unsafeInlineIO $
309 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
312-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
313-- at index @i@ and reading up to @count@ elements in the forward direction
314-- ending at the index @i + count - 1@.
317{-# INLINE readSlice #-}
318readSlice :: (IsStream t, Monad m, Storable a)
319 => Array a -> Int -> Int -> t m a
320readSlice arr i len = undefined
322-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
323-- index @i@ and reading up to @count@ elements in the reverse direction ending
324-- at the index @i - count + 1@.
327{-# INLINE readSliceRev #-}
328readSliceRev :: (IsStream t, Monad m, Storable a)
329 => Array a -> Int -> Int -> t m a
330readSliceRev arr i len = undefined
333-- | /O(1)/ Write the given element at the given index in the array.
334-- Performs in-place mutation of the array.
337{-# INLINE _writeIndex #-}
338_writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
339_writeIndex arr i a = do
340 let maxIndex = length arr - 1
342 then error "writeIndex: negative array index"
344 then error $ "writeIndex: specified array index " ++ show i
345 ++ " is beyond the maximum index " ++ show maxIndex
347 liftIO $ withForeignPtr (aStart arr) $ \p ->
351-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
352-- starting at index @i@ and writing up to @count@ elements in the forward
353-- direction ending at the index @i + count - 1@.
356{-# INLINE writeSlice #-}
357writeSlice :: (IsStream t, Monad m, Storable a)
358 => Array a -> Int -> Int -> t m a -> m ()
359writeSlice arr i len s = undefined
361-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
362-- starting at index @i@ and writing up to @count@ elements in the reverse
363-- direction ending at the index @i - count + 1@.
366{-# INLINE writeSliceRev #-}
367writeSliceRev :: (IsStream t, Monad m, Storable a)
368 => Array a -> Int -> Int -> t m a -> m ()
369writeSliceRev arr i len s = undefined
372-------------------------------------------------------------------------------
373-- Transform via stream operations
374-------------------------------------------------------------------------------
376-- for non-length changing operations we can use the original length for
377-- allocation. If we can predict the length then we can use the prediction for
378-- new allocation. Otherwise we can use a hint and adjust dynamically.
381-- | Transform an array into another array using a pipe transformation
385{-# INLINE runPipe #-}
386runPipe :: (MonadIO m, Storable a, Storable b)
387 => Pipe m a b -> Array a -> m (Array b)
388runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
391-- | Transform an array into another array using a stream transformation
395{-# INLINE _runTransform #-}
396_runTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
397 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
399 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
402-- | Fold an array using a 'Fold'.
405{-# INLINE _runFold #-}
406_runFold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
407_runFold f arr = P.runFold f $ (A.read arr :: Serial.SerialT m a)
409-- | Fold an array using a stream fold operation.
412{-# INLINE _runStreamFold #-}
413_runStreamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
414_runStreamFold 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