on 623b3fd help sign in
429 lines 15 kB history raw
1{-# LANGUAGE BangPatterns #-}
2{-# LANGUAGE CPP #-}
3{-# LANGUAGE MagicHash #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE UnboxedTuples #-}
6{-# LANGUAGE ScopedTypeVariables #-}
8#include "inline.hs"
10-- |
11-- Module : Streamly.Memory.Array
12-- Copyright : (c) 2019 Harendra Kumar
13--
14-- License : BSD3
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
17-- Portability : GHC
18--
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.
29--
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.
35--
36-- This module is designed to be imported qualified:
37--
38-- > import qualified Streamly.Array as A
40-- To summarize:
41--
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
46--
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.
52--
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
60-- contiguous memory.
62module Streamly.Memory.Array
63 (
64 Array
66 -- , defaultChunkSize
68 -- * Arrays
69 -- ** Construction
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.
77 -- Pure List APIs
78 , A.fromListN
79 , A.fromList
81 -- Monadic APIs
82 -- , newArray
83 , A.writeN -- drop new
84 , A.write -- full buffer
85 -- , writeLastN -- drop old (ring buffer)
87 -- Stream Folds
88 -- , writeNS
89 -- , writeS
91 -- ** Elimination
92 -- 'GHC.Exts.toList' from "GHC.Exts" can be used to convert an array to a
93 -- list.
95 , A.toList
96 , A.read
97 , readRev
99 -- ** Random Access
100 , length
101 -- , (!!)
103 , readIndex
104 {-
105 , readSlice
106 , readSliceRev
107 -}
109 -- , writeIndex
110 {-
111 , writeSlice
112 , writeSliceRev
113 -}
115 {-
116 -- * Immutable Transformations
117 , runTransform
119 -- * Folding Arrays
120 -- , runStreamFold
121 , runFold
122 -}
124 -- * Streams of Arrays
125 -- -- ** Creation
126 -- , AS.arraysOf
128 -- -- ** Elimination
129 -- , AS.concat
130 -- , AS.concatRev
131 -- , AS.toArray
133 -- ** Transformation
134 , AS.splitOn
135 , AS.splitOnSuffix
136 -- , AS.compact -- compact
137 )
138where
140import Control.Monad.IO.Class (MonadIO(..))
141-- import Data.Functor.Identity (Identity)
142import Foreign.ForeignPtr (withForeignPtr)
143import Foreign.Storable (Storable(..))
144import Prelude hiding (length, null, last, map, (!!), read, concat)
146import Streamly.Internal.Memory.Array.Types (Array(..), length)
147import Streamly.Streams.Serial (SerialT)
148import Streamly.Streams.StreamK.Type (IsStream)
149import Streamly.Internal.Data.Fold.Types (Fold(..))
151import qualified Streamly.Internal.Memory.Array.Types as A
152import qualified Streamly.Internal.Memory.ArrayStream as AS
153import qualified Streamly.Streams.Prelude as P
154import qualified Streamly.Streams.Serial as Serial
155import qualified Streamly.Streams.StreamD as D
157-------------------------------------------------------------------------------
158-- Construction
159-------------------------------------------------------------------------------
161{-
162-- | Create a new uninitialized array of given length.
163--
164-- @since 0.7.0
165newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
166newArray len = undefined
167-}
169-- | Create an 'Array' from the first N elements of a stream. The array is
170-- allocated to size N, if the stream terminates before N elements then the
171-- array may hold less than N elements.
172--
173-- @since 0.7.0
174{-# INLINE _writeNS #-}
175_writeNS :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
176_writeNS n m = do
177 if n < 0 then error "writeN: negative write count specified" else return ()
178 A.fromStreamDN n $ D.toStreamD m
180-- | Create an 'Array' from a stream. This is useful when we want to create a
181-- single array from a stream of unknown size. 'writeN' is at least twice
182-- as efficient when the size is already known.
183--
184-- Note that if the input stream is too large memory allocation for the array
185-- may fail. When the stream size is not known, `arraysOf` followed by
186-- processing of indvidual arrays in the resulting stream should be preferred.
187--
188{-# INLINE _writeS #-}
189_writeS :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
190_writeS = P.runFold A.write
191-- write m = A.fromStreamD $ D.toStreamD m
193-------------------------------------------------------------------------------
194-- Elimination
195-------------------------------------------------------------------------------
197-- | Convert an 'Array' into a stream in reverse order.
198--
199-- @since 0.7.0
200{-# INLINE_EARLY readRev #-}
201readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
202readRev = D.fromStreamD . A.toStreamDRev
203-- XXX add fallback to StreamK rule
204-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
205-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
207{-# INLINE _null #-}
208_null :: Storable a => Array a -> Bool
209_null arr = length arr == 0
211{-# INLINE _last #-}
212_last :: Storable a => Array a -> Maybe a
213_last arr = readIndex arr (length arr - 1)
215-------------------------------------------------------------------------------
216-- Random Access
217-------------------------------------------------------------------------------
219-------------------------------------------------------------------------------
220-- Searching
221-------------------------------------------------------------------------------
223{-
224-- | Perform a binary search in the array to find an element.
225bsearch :: a -> Array a -> Maybe Bool
226bsearch = undefined
228-- | Perform a binary search in the array to find an element index.
229{-# INLINE elemIndex #-}
230bsearchIndex :: a -> Array a -> Maybe Int
231bsearchIndex elem arr = undefined
233-- find/findIndex etc can potentially be implemented more efficiently on arrays
234-- compared to streams by using SIMD instructions.
236find :: (a -> Bool) -> Array a -> Bool
237find = undefined
239findIndex :: (a -> Bool) -> Array a -> Maybe Int
240findIndex = undefined
242findIndices :: (a -> Bool) -> Array a -> Array Int
243findIndices = undefined
244-}
246-------------------------------------------------------------------------------
247-- Folds
248-------------------------------------------------------------------------------
250-- XXX We can potentially use SIMD instructions on arrays to fold faster.
252-------------------------------------------------------------------------------
253-- Slice and splice
254-------------------------------------------------------------------------------
256{-
257slice :: Int -> Int -> Array a
258slice begin end arr = undefined
260splitAt :: Int -> Array a -> (Array a, Array a)
261splitAt i arr = undefined
263-- XXX This operation can be performed efficiently via streams.
264-- | Append two arrays together to create a single array.
265splice :: Array a -> Array a -> Array a
266splice arr1 arr2 = undefined
268-------------------------------------------------------------------------------
269-- In-place mutation APIs
270-------------------------------------------------------------------------------
272-- | Partition an array into two halves using a partitioning predicate. The
273-- first half retains values where the predicate is 'False' and the second half
274-- retains values where the predicate is 'True'.
275{-# INLINE partitionBy #-}
276partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
277partitionBy f arr = undefined
279-- | Shuffle corresponding elements from two arrays using a shuffle function.
280-- If the shuffle function returns 'False' then do nothing otherwise swap the
281-- elements. This can be used in a bottom up fold to shuffle or reorder the
282-- elements.
283shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
284shuffleBy f arr1 arr2 = undefined
286-- XXX we can also make the folds partial by stopping at a certain level.
287--
288-- | Perform a top down hierarchical recursive partitioning fold of items in
289-- the container using the given function as the partition function.
290--
291-- This will perform a quick sort if the partition function is
292-- 'partitionBy (< pivot)'.
293--
294-- @since 0.7.0
295{-# INLINABLE foldtWith #-}
296foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
297foldtWith level f = undefined
299-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
300-- indicates the level in the tree where the fold would stop.
301--
302-- This will perform a random shuffle if the shuffle function is random.
303-- If we stop at level 0 and repeatedly apply the function then we can do a
304-- bubble sort.
305foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
306foldbWith level f = undefined
307-}
309-- XXX consider the bulk update/accumulation/permutation APIs from vector.
311-------------------------------------------------------------------------------
312-- Random reads and writes
313-------------------------------------------------------------------------------
315-- | /O(1)/ Lookup the element at the given index, starting from 0.
316--
317-- @since 0.7.0
318{-# INLINE readIndex #-}
319readIndex :: Storable a => Array a -> Int -> Maybe a
320readIndex arr i =
321 if i < 0 || i > length arr - 1
322 then Nothing
323 else A.unsafeInlineIO $
324 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
326{-
327-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
328-- at index @i@ and reading up to @count@ elements in the forward direction
329-- ending at the index @i + count - 1@.
330--
331-- @since 0.7.0
332{-# INLINE readSlice #-}
333readSlice :: (IsStream t, Monad m, Storable a)
334 => Array a -> Int -> Int -> t m a
335readSlice arr i len = undefined
337-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
338-- index @i@ and reading up to @count@ elements in the reverse direction ending
339-- at the index @i - count + 1@.
340--
341-- @since 0.7.0
342{-# INLINE readSliceRev #-}
343readSliceRev :: (IsStream t, Monad m, Storable a)
344 => Array a -> Int -> Int -> t m a
345readSliceRev arr i len = undefined
346-}
348-- | /O(1)/ Write the given element at the given index in the array.
349-- Performs in-place mutation of the array.
350--
351-- @since 0.7.0
352{-# INLINE _writeIndex #-}
353_writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
354_writeIndex arr i a = do
355 let maxIndex = length arr - 1
356 if i < 0
357 then error "writeIndex: negative array index"
358 else if i > maxIndex
359 then error $ "writeIndex: specified array index " ++ show i
360 ++ " is beyond the maximum index " ++ show maxIndex
361 else
362 liftIO $ withForeignPtr (aStart arr) $ \p ->
363 pokeElemOff p i a
365{-
366-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
367-- starting at index @i@ and writing up to @count@ elements in the forward
368-- direction ending at the index @i + count - 1@.
369--
370-- @since 0.7.0
371{-# INLINE writeSlice #-}
372writeSlice :: (IsStream t, Monad m, Storable a)
373 => Array a -> Int -> Int -> t m a -> m ()
374writeSlice arr i len s = undefined
376-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
377-- starting at index @i@ and writing up to @count@ elements in the reverse
378-- direction ending at the index @i - count + 1@.
379--
380-- @since 0.7.0
381{-# INLINE writeSliceRev #-}
382writeSliceRev :: (IsStream t, Monad m, Storable a)
383 => Array a -> Int -> Int -> t m a -> m ()
384writeSliceRev arr i len s = undefined
385-}
387-------------------------------------------------------------------------------
388-- Transform via stream operations
389-------------------------------------------------------------------------------
391-- for non-length changing operations we can use the original length for
392-- allocation. If we can predict the length then we can use the prediction for
393-- new allocation. Otherwise we can use a hint and adjust dynamically.
395{-
396-- | Transform an array into another array using a pipe transformation
397-- operation.
398--
399-- @since 0.7.0
400{-# INLINE runPipe #-}
401runPipe :: (MonadIO m, Storable a, Storable b)
402 => Pipe m a b -> Array a -> m (Array b)
403runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
404-}
406-- | Transform an array into another array using a stream transformation
407-- operation.
408--
409-- @since 0.7.0
410{-# INLINE _runTransform #-}
411_runTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
412 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
413_runTransform f arr =
414 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
415 $ f (A.read arr)
417-- | Fold an array using a 'Fold'.
418--
419-- @since 0.7.0
420{-# INLINE _runFold #-}
421_runFold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
422_runFold f arr = P.runFold f $ (A.read arr :: Serial.SerialT m a)
424-- | Fold an array using a stream fold operation.
425--
426-- @since 0.7.0
427{-# INLINE _runStreamFold #-}
428_runStreamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
429_runStreamFold f arr = f (A.read arr)