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
124 -- * Streams of Arrays
135 , AS.compact -- compact
139import Control.Monad.IO.Class (MonadIO(..))
140-- import Data.Functor.Identity (Identity)
141import Foreign.ForeignPtr (withForeignPtr)
142import Foreign.Storable (Storable(..))
143import Prelude hiding (length, null, last, map, (!!), read, concat)
145import Streamly.Memory.Array.Types (Array(..), length)
146import Streamly.Streams.Serial (SerialT)
147import Streamly.Streams.StreamK.Type (IsStream)
148import Streamly.Fold.Types (Fold(..))
150import qualified Streamly.Memory.Array.Types as A
151import qualified Streamly.Memory.ArrayStream as AS
152import qualified Streamly.Streams.Prelude as P
153import qualified Streamly.Streams.Serial as Serial
154import qualified Streamly.Streams.StreamD as D
156-------------------------------------------------------------------------------
158-------------------------------------------------------------------------------
161-- | Create a new uninitialized array of given length.
164newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
165newArray len = undefined
168-- | Create an 'Array' from the first N elements of a stream. The array is
169-- allocated to size N, if the stream terminates before N elements then the
170-- array may hold less than N elements.
173{-# INLINE _writeNS #-}
174_writeNS :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
176 if n < 0 then error "writeN: negative write count specified" else return ()
177 A.fromStreamDN n $ D.toStreamD m
179-- | Create an 'Array' from a stream. This is useful when we want to create a
180-- single array from a stream of unknown size. 'writeN' is at least twice
181-- as efficient when the size is already known.
183-- Note that if the input stream is too large memory allocation for the array
184-- may fail. When the stream size is not known, `arraysOf` followed by
185-- processing of indvidual arrays in the resulting stream should be preferred.
187{-# INLINE _writeS #-}
188_writeS :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
189_writeS = P.runFold A.write
190-- write m = A.fromStreamD $ D.toStreamD m
192-------------------------------------------------------------------------------
194-------------------------------------------------------------------------------
196-- | Convert an 'Array' into a stream in reverse order.
199{-# INLINE_EARLY readRev #-}
200readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
201readRev = D.fromStreamD . A.toStreamDRev
202-- XXX add fallback to StreamK rule
203-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
204-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
207_null :: Storable a => Array a -> Bool
208_null arr = length arr == 0
211_last :: Storable a => Array a -> Maybe a
212_last arr = readIndex arr (length arr - 1)
214-------------------------------------------------------------------------------
216-------------------------------------------------------------------------------
218-------------------------------------------------------------------------------
220-------------------------------------------------------------------------------
223-- | Perform a binary search in the array to find an element.
224bsearch :: a -> Array a -> Maybe Bool
227-- | Perform a binary search in the array to find an element index.
228{-# INLINE elemIndex #-}
229bsearchIndex :: a -> Array a -> Maybe Int
230bsearchIndex elem arr = undefined
232-- find/findIndex etc can potentially be implemented more efficiently on arrays
233-- compared to streams by using SIMD instructions.
235find :: (a -> Bool) -> Array a -> Bool
238findIndex :: (a -> Bool) -> Array a -> Maybe Int
241findIndices :: (a -> Bool) -> Array a -> Array Int
242findIndices = undefined
245-------------------------------------------------------------------------------
247-------------------------------------------------------------------------------
249-- XXX We can potentially use SIMD instructions on arrays to fold faster.
251-------------------------------------------------------------------------------
253-------------------------------------------------------------------------------
256slice :: Int -> Int -> Array a
257slice begin end arr = undefined
259splitAt :: Int -> Array a -> (Array a, Array a)
260splitAt i arr = undefined
262-- XXX This operation can be performed efficiently via streams.
263-- | Append two arrays together to create a single array.
264splice :: Array a -> Array a -> Array a
265splice arr1 arr2 = undefined
267-------------------------------------------------------------------------------
268-- In-place mutation APIs
269-------------------------------------------------------------------------------
271-- | Partition an array into two halves using a partitioning predicate. The
272-- first half retains values where the predicate is 'False' and the second half
273-- retains values where the predicate is 'True'.
274{-# INLINE partitionBy #-}
275partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
276partitionBy f arr = undefined
278-- | Shuffle corresponding elements from two arrays using a shuffle function.
279-- If the shuffle function returns 'False' then do nothing otherwise swap the
280-- elements. This can be used in a bottom up fold to shuffle or reorder the
282shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
283shuffleBy f arr1 arr2 = undefined
285-- XXX we can also make the folds partial by stopping at a certain level.
287-- | Perform a top down hierarchical recursive partitioning fold of items in
288-- the container using the given function as the partition function.
290-- This will perform a quick sort if the partition function is
291-- 'partitionBy (< pivot)'.
294{-# INLINABLE foldtWith #-}
295foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
296foldtWith level f = undefined
298-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
299-- indicates the level in the tree where the fold would stop.
301-- This will perform a random shuffle if the shuffle function is random.
302-- If we stop at level 0 and repeatedly apply the function then we can do a
304foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
305foldbWith level f = undefined
308-- XXX consider the bulk update/accumulation/permutation APIs from vector.
310-------------------------------------------------------------------------------
311-- Random reads and writes
312-------------------------------------------------------------------------------
314-- | /O(1)/ Lookup the element at the given index, starting from 0.
317{-# INLINE readIndex #-}
318readIndex :: Storable a => Array a -> Int -> Maybe a
320 if i < 0 || i > length arr - 1
322 else A.unsafeInlineIO $
323 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
326-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
327-- at index @i@ and reading up to @count@ elements in the forward direction
328-- ending at the index @i + count - 1@.
331{-# INLINE readSlice #-}
332readSlice :: (IsStream t, Monad m, Storable a)
333 => Array a -> Int -> Int -> t m a
334readSlice arr i len = undefined
336-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
337-- index @i@ and reading up to @count@ elements in the reverse direction ending
338-- at the index @i - count + 1@.
341{-# INLINE readSliceRev #-}
342readSliceRev :: (IsStream t, Monad m, Storable a)
343 => Array a -> Int -> Int -> t m a
344readSliceRev arr i len = undefined
347-- | /O(1)/ Write the given element at the given index in the array.
348-- Performs in-place mutation of the array.
351{-# INLINE _writeIndex #-}
352_writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
353_writeIndex arr i a = do
354 let maxIndex = length arr - 1
356 then error "writeIndex: negative array index"
358 then error $ "writeIndex: specified array index " ++ show i
359 ++ " is beyond the maximum index " ++ show maxIndex
361 liftIO $ withForeignPtr (aStart arr) $ \p ->
365-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
366-- starting at index @i@ and writing up to @count@ elements in the forward
367-- direction ending at the index @i + count - 1@.
370{-# INLINE writeSlice #-}
371writeSlice :: (IsStream t, Monad m, Storable a)
372 => Array a -> Int -> Int -> t m a -> m ()
373writeSlice arr i len s = undefined
375-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
376-- starting at index @i@ and writing up to @count@ elements in the reverse
377-- direction ending at the index @i - count + 1@.
380{-# INLINE writeSliceRev #-}
381writeSliceRev :: (IsStream t, Monad m, Storable a)
382 => Array a -> Int -> Int -> t m a -> m ()
383writeSliceRev arr i len s = undefined
386-------------------------------------------------------------------------------
387-- Transform via stream operations
388-------------------------------------------------------------------------------
390-- for non-length changing operations we can use the original length for
391-- allocation. If we can predict the length then we can use the prediction for
392-- new allocation. Otherwise we can use a hint and adjust dynamically.
395-- | Transform an array into another array using a pipe transformation
399{-# INLINE runPipe #-}
400runPipe :: (MonadIO m, Storable a, Storable b)
401 => Pipe m a b -> Array a -> m (Array b)
402runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
405-- | Transform an array into another array using a stream transformation
409{-# INLINE _runTransform #-}
410_runTransform :: (MonadIO m, Storable a, Storable b)
411 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
412_runTransform f arr = P.runFold (A.toArrayMinChunk (length arr)) $ f (A.read arr)
414-- | Fold an array using a 'Fold'.
417{-# INLINE _runFold #-}
418_runFold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
419_runFold f arr = P.runFold f $ (A.read arr :: Serial.SerialT m a)
421-- | Fold an array using a stream fold operation.
424{-# INLINE _runStreamFold #-}
425_runStreamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
426_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