on d030361 help sign in
458 lines 16 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 -- * Construction
69 -- | When performance matters, the fastest way to generate an array is
70 -- 'writeN'. For regular use, 'IsList' and 'IsString' instances can be
71 -- used to conveniently construct arrays from literal values.
72 -- 'OverloadedLists' extension or 'fromList' can be used to construct an
73 -- array from a list literal. Similarly, 'OverloadedStrings' extension or
74 -- 'fromList' can be used to construct an array from a string literal.
76 -- Pure List APIs
77 , A.fromListN
78 , A.fromList
80 -- Monadic APIs
81 -- , newArray
82 , A.writeN
83 , write
85 -- Stream Folds
86 -- , writeNS
87 -- , writeS
89 -- * Elimination
90 -- 'GHC.Exts.toList' from "GHC.Exts" can be used to convert an array to a
91 -- list.
93 , A.toList
94 , A.read
95 , readRev
97 -- * Random Access
98 , length
99 -- , (!!)
101 , readIndex
102 {-
103 , readSlice
104 , readSliceRev
105 -}
107 -- , writeIndex
108 {-
109 , writeSlice
110 , writeSliceRev
111 -}
113 {-
114 -- * Immutable Transformations
115 , runTransform
117 -- * Folding Arrays
118 -- , runStreamFold
119 , runFold
120 -}
121 )
122where
124import Control.Monad (when)
125import Control.Monad.IO.Class (MonadIO(..))
126-- import Data.Functor.Identity (Identity)
127import Foreign.ForeignPtr (withForeignPtr)
128import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
129import Foreign.Ptr (minusPtr, plusPtr)
130import Foreign.Storable (Storable(..))
131import Prelude hiding (length, null, last, map, (!!), read)
133import Streamly.Memory.Array.Types (Array(..), length)
134import Streamly.Streams.Serial (SerialT)
135import Streamly.Streams.StreamK.Type (IsStream)
136import Streamly.Fold.Types (Fold(..))
138import qualified Streamly.Memory.Array.Types as A
139import qualified Streamly.Streams.Prelude as P
140import qualified Streamly.Streams.Serial as Serial
141import qualified Streamly.Streams.StreamD as D
143-------------------------------------------------------------------------------
144-- Construction
145-------------------------------------------------------------------------------
147{-
148-- | Create a new uninitialized array of given length.
149--
150-- @since 0.7.0
151newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
152newArray len = undefined
153-}
155-- | Create an 'Array' from the first N elements of a stream. The array is
156-- allocated to size N, if the stream terminates before N elements then the
157-- array may hold less than N elements.
158--
159-- @since 0.7.0
160{-# INLINE _writeNS #-}
161_writeNS :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
162_writeNS n m = do
163 if n < 0 then error "writeN: negative write count specified" else return ()
164 A.fromStreamDN n $ D.toStreamD m
166-- XXX The realloc based implementation needs to make one extra copy if we use
167-- shrinkToFit. On the other hand, the stream of arrays implementation may
168-- buffer the array chunk pointers in memory but it does not have to shrink as
169-- we know the exact size in the end. However, memory copying does not seems to
170-- be as expensive as the allocations. Therefore, we need to reduce the number
171-- of allocations instead. Also, the size of allocations matters, right sizing
172-- an allocation even at the cost of copying sems to help. Should be measured
173-- on a big stream with heavy calls to toArray to see the effect.
174--
175-- XXX check if GHC's memory allocator is efficient enough. We can try the C
176-- malloc to compare against.
178{-# INLINE_NORMAL toArrayMinChunk #-}
179toArrayMinChunk :: forall m a. (MonadIO m, Storable a)
180 => Int -> Fold m a (Array a)
181-- toArrayMinChunk n = FL.mapM spliceArrays $ toArraysOf n
182toArrayMinChunk elemCount = Fold step initial extract
184 where
186 insertElem (Array start end bound) x = do
187 liftIO $ poke end x
188 return $ Array start (end `plusPtr` sizeOf (undefined :: a)) bound
190 initial = do
191 when (elemCount < 0) $ error "toArrayMinChunk: elemCount is negative"
192 liftIO $ A.newArray elemCount
193 step arr@(Array start end bound) x | end == bound = do
194 let p = unsafeForeignPtrToPtr start
195 oldSize = end `minusPtr` p
196 newSize = max (oldSize * 2) 1
197 arr1 <- liftIO $ A.realloc newSize arr
198 insertElem arr1 x
199 step arr x = insertElem arr x
200 extract = liftIO . A.shrinkToFit
202-- | Fold the whole input to a single array.
203--
204-- /Caution! Do not use this on infinite streams./
205--
206-- @since 0.7.0
207{-# INLINE write #-}
208write :: forall m a. (MonadIO m, Storable a) => Fold m a (Array a)
209write = toArrayMinChunk (A.bytesToElemCount (undefined :: a) (A.mkChunkSize 1024))
211-- | Create an 'Array' from a stream. This is useful when we want to create a
212-- single array from a stream of unknown size. 'writeN' is at least twice
213-- as efficient when the size is already known.
214--
215-- Note that if the input stream is too large memory allocation for the array
216-- may fail. When the stream size is not known, `arraysOf` followed by
217-- processing of indvidual arrays in the resulting stream should be preferred.
218--
219{-# INLINE _writeS #-}
220_writeS :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
221_writeS = P.runFold write
222-- write m = A.fromStreamD $ D.toStreamD m
224-------------------------------------------------------------------------------
225-- Elimination
226-------------------------------------------------------------------------------
228-- | Convert an 'Array' into a stream in reverse order.
229--
230-- @since 0.7.0
231{-# INLINE_EARLY readRev #-}
232readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
233readRev = D.fromStreamD . A.toStreamDRev
234-- XXX add fallback to StreamK rule
235-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
236-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
238{-# INLINE _null #-}
239_null :: Storable a => Array a -> Bool
240_null arr = length arr == 0
242{-# INLINE _last #-}
243_last :: (MonadIO m, Storable a) => Array a -> m (Maybe a)
244_last arr = readIndex arr (length arr - 1)
246-------------------------------------------------------------------------------
247-- Random Access
248-------------------------------------------------------------------------------
250-------------------------------------------------------------------------------
251-- Searching
252-------------------------------------------------------------------------------
254{-
255-- | Perform a binary search in the array to find an element.
256bsearch :: a -> Array a -> Maybe Bool
257bsearch = undefined
259-- | Perform a binary search in the array to find an element index.
260{-# INLINE elemIndex #-}
261bsearchIndex :: a -> Array a -> Maybe Int
262bsearchIndex elem arr = undefined
264-- find/findIndex etc can potentially be implemented more efficiently on arrays
265-- compared to streams by using SIMD instructions.
267find :: (a -> Bool) -> Array a -> Bool
268find = undefined
270findIndex :: (a -> Bool) -> Array a -> Maybe Int
271findIndex = undefined
273findIndices :: (a -> Bool) -> Array a -> Array Int
274findIndices = undefined
275-}
277-------------------------------------------------------------------------------
278-- Folds
279-------------------------------------------------------------------------------
281-- XXX We can potentially use SIMD instructions on arrays to fold faster.
283-------------------------------------------------------------------------------
284-- Slice and splice
285-------------------------------------------------------------------------------
287{-
288slice :: Int -> Int -> Array a
289slice begin end arr = undefined
291splitAt :: Int -> Array a -> (Array a, Array a)
292splitAt i arr = undefined
294-- XXX This operation can be performed efficiently via streams.
295-- | Append two arrays together to create a single array.
296splice :: Array a -> Array a -> Array a
297splice arr1 arr2 = undefined
299-------------------------------------------------------------------------------
300-- In-place mutation APIs
301-------------------------------------------------------------------------------
303-- | Partition an array into two halves using a partitioning predicate. The
304-- first half retains values where the predicate is 'False' and the second half
305-- retains values where the predicate is 'True'.
306{-# INLINE partitionBy #-}
307partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
308partitionBy f arr = undefined
310-- | Shuffle corresponding elements from two arrays using a shuffle function.
311-- If the shuffle function returns 'False' then do nothing otherwise swap the
312-- elements. This can be used in a bottom up fold to shuffle or reorder the
313-- elements.
314shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
315shuffleBy f arr1 arr2 = undefined
317-- XXX we can also make the folds partial by stopping at a certain level.
318--
319-- | Perform a top down hierarchical recursive partitioning fold of items in
320-- the container using the given function as the partition function.
321--
322-- This will perform a quick sort if the partition function is
323-- 'partitionBy (< pivot)'.
324--
325-- @since 0.7.0
326{-# INLINABLE foldtWith #-}
327foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
328foldtWith level f = undefined
330-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
331-- indicates the level in the tree where the fold would stop.
332--
333-- This will perform a random shuffle if the shuffle function is random.
334-- If we stop at level 0 and repeatedly apply the function then we can do a
335-- bubble sort.
336foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
337foldbWith level f = undefined
338-}
340-- XXX consider the bulk update/accumulation/permutation APIs from vector.
342-------------------------------------------------------------------------------
343-- Random reads and writes
344-------------------------------------------------------------------------------
346-- | /O(1)/ Lookup the element at the given index.
347--
348-- @since 0.7.0
349{-# INLINE readIndex #-}
350readIndex :: (MonadIO m, Storable a) => Array a -> Int -> m (Maybe a)
351readIndex arr i =
352 if i < 0 || i > length arr - 1
353 then return Nothing
354 else liftIO $ withForeignPtr (aStart arr) $ \p ->
355 fmap Just $ peekElemOff p i
357{-
358-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
359-- at index @i@ and reading up to @count@ elements in the forward direction
360-- ending at the index @i + count - 1@.
361--
362-- @since 0.7.0
363{-# INLINE readSlice #-}
364readSlice :: (IsStream t, Monad m, Storable a)
365 => Array a -> Int -> Int -> t m a
366readSlice arr i len = undefined
368-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
369-- index @i@ and reading up to @count@ elements in the reverse direction ending
370-- at the index @i - count + 1@.
371--
372-- @since 0.7.0
373{-# INLINE readSliceRev #-}
374readSliceRev :: (IsStream t, Monad m, Storable a)
375 => Array a -> Int -> Int -> t m a
376readSliceRev arr i len = undefined
377-}
379-- | /O(1)/ Write the given element at the given index in the array.
380-- Performs in-place mutation of the array.
381--
382-- @since 0.7.0
383{-# INLINE _writeIndex #-}
384_writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
385_writeIndex arr i a = do
386 let maxIndex = length arr - 1
387 if i < 0
388 then error "writeIndex: negative array index"
389 else if i > maxIndex
390 then error $ "writeIndex: specified array index " ++ show i
391 ++ " is beyond the maximum index " ++ show maxIndex
392 else
393 liftIO $ withForeignPtr (aStart arr) $ \p ->
394 pokeElemOff p i a
396{-
397-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
398-- starting at index @i@ and writing up to @count@ elements in the forward
399-- direction ending at the index @i + count - 1@.
400--
401-- @since 0.7.0
402{-# INLINE writeSlice #-}
403writeSlice :: (IsStream t, Monad m, Storable a)
404 => Array a -> Int -> Int -> t m a -> m ()
405writeSlice arr i len s = undefined
407-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
408-- starting at index @i@ and writing up to @count@ elements in the reverse
409-- direction ending at the index @i - count + 1@.
410--
411-- @since 0.7.0
412{-# INLINE writeSliceRev #-}
413writeSliceRev :: (IsStream t, Monad m, Storable a)
414 => Array a -> Int -> Int -> t m a -> m ()
415writeSliceRev arr i len s = undefined
416-}
418-------------------------------------------------------------------------------
419-- Transform via stream operations
420-------------------------------------------------------------------------------
422-- for non-length changing operations we can use the original length for
423-- allocation. If we can predict the length then we can use the prediction for
424-- new allocation. Otherwise we can use a hint and adjust dynamically.
426{-
427-- | Transform an array into another array using a pipe transformation
428-- operation.
429--
430-- @since 0.7.0
431{-# INLINE runPipe #-}
432runPipe :: (MonadIO m, Storable a, Storable b)
433 => Pipe m a b -> Array a -> m (Array b)
434runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
435-}
437-- | Transform an array into another array using a stream transformation
438-- operation.
439--
440-- @since 0.7.0
441{-# INLINE _runTransform #-}
442_runTransform :: (MonadIO m, Storable a, Storable b)
443 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
444_runTransform f arr = P.runFold (toArrayMinChunk (length arr)) $ f (A.read arr)
446-- | Fold an array using a 'Fold'.
447--
448-- @since 0.7.0
449{-# INLINE _runFold #-}
450_runFold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
451_runFold f arr = P.runFold f $ (A.read arr :: Serial.SerialT m a)
453-- | Fold an array using a stream fold operation.
454--
455-- @since 0.7.0
456{-# INLINE _runStreamFold #-}
457_runStreamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
458_runStreamFold f arr = f (A.read arr)