on 006fc5f help sign in
426 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.compact -- compact
136 )
137where
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-------------------------------------------------------------------------------
157-- Construction
158-------------------------------------------------------------------------------
160{-
161-- | Create a new uninitialized array of given length.
162--
163-- @since 0.7.0
164newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
165newArray len = undefined
166-}
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.
171--
172-- @since 0.7.0
173{-# INLINE _writeNS #-}
174_writeNS :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
175_writeNS n m = do
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.
182--
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.
186--
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-------------------------------------------------------------------------------
193-- Elimination
194-------------------------------------------------------------------------------
196-- | Convert an 'Array' into a stream in reverse order.
197--
198-- @since 0.7.0
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 #-}
206{-# INLINE _null #-}
207_null :: Storable a => Array a -> Bool
208_null arr = length arr == 0
210{-# INLINE _last #-}
211_last :: Storable a => Array a -> Maybe a
212_last arr = readIndex arr (length arr - 1)
214-------------------------------------------------------------------------------
215-- Random Access
216-------------------------------------------------------------------------------
218-------------------------------------------------------------------------------
219-- Searching
220-------------------------------------------------------------------------------
222{-
223-- | Perform a binary search in the array to find an element.
224bsearch :: a -> Array a -> Maybe Bool
225bsearch = undefined
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
236find = undefined
238findIndex :: (a -> Bool) -> Array a -> Maybe Int
239findIndex = undefined
241findIndices :: (a -> Bool) -> Array a -> Array Int
242findIndices = undefined
243-}
245-------------------------------------------------------------------------------
246-- Folds
247-------------------------------------------------------------------------------
249-- XXX We can potentially use SIMD instructions on arrays to fold faster.
251-------------------------------------------------------------------------------
252-- Slice and splice
253-------------------------------------------------------------------------------
255{-
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
281-- elements.
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.
286--
287-- | Perform a top down hierarchical recursive partitioning fold of items in
288-- the container using the given function as the partition function.
289--
290-- This will perform a quick sort if the partition function is
291-- 'partitionBy (< pivot)'.
292--
293-- @since 0.7.0
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.
300--
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
303-- bubble sort.
304foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
305foldbWith level f = undefined
306-}
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.
315--
316-- @since 0.7.0
317{-# INLINE readIndex #-}
318readIndex :: Storable a => Array a -> Int -> Maybe a
319readIndex arr i =
320 if i < 0 || i > length arr - 1
321 then Nothing
322 else A.unsafeInlineIO $
323 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
325{-
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@.
329--
330-- @since 0.7.0
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@.
339--
340-- @since 0.7.0
341{-# INLINE readSliceRev #-}
342readSliceRev :: (IsStream t, Monad m, Storable a)
343 => Array a -> Int -> Int -> t m a
344readSliceRev arr i len = undefined
345-}
347-- | /O(1)/ Write the given element at the given index in the array.
348-- Performs in-place mutation of the array.
349--
350-- @since 0.7.0
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
355 if i < 0
356 then error "writeIndex: negative array index"
357 else if i > maxIndex
358 then error $ "writeIndex: specified array index " ++ show i
359 ++ " is beyond the maximum index " ++ show maxIndex
360 else
361 liftIO $ withForeignPtr (aStart arr) $ \p ->
362 pokeElemOff p i a
364{-
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@.
368--
369-- @since 0.7.0
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@.
378--
379-- @since 0.7.0
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
384-}
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.
394{-
395-- | Transform an array into another array using a pipe transformation
396-- operation.
397--
398-- @since 0.7.0
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)
403-}
405-- | Transform an array into another array using a stream transformation
406-- operation.
407--
408-- @since 0.7.0
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'.
415--
416-- @since 0.7.0
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.
422--
423-- @since 0.7.0
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)