on ecb846d help sign in
468 lines 16 kB history raw
1{-# OPTIONS_HADDOCK hide #-}
2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE CPP #-}
4{-# LANGUAGE MagicHash #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE UnboxedTuples #-}
7{-# LANGUAGE ScopedTypeVariables #-}
9#include "inline.hs"
11-- |
12-- Module : Streamly.Internal.Memory.Array
13-- Copyright : (c) 2019 Composewell Technologies
14--
15-- License : BSD3
16-- Maintainer : streamly@composewell.com
17-- Stability : experimental
18-- Portability : GHC
19--
20-- To summarize:
21--
22-- * Arrays are finite and fixed in size
23-- * provide /O(1)/ access to elements
24-- * store only data and not functions
25-- * provide efficient IO interfacing
26--
27-- 'Foldable' instance is not provided because the implementation would be much
28-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
29-- instances should be used with care; concatenating arrays using binary
30-- operations can be highly inefficient. Instead, use
31-- 'Streamly.Internal.Memory.ArrayStream.toArray' to concatenate N arrays at
32-- once.
33--
34-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
35-- single byte) are only as good as holding those elements in a Haskell list.
36-- However, small arrays can be compacted into large ones to reduce the
37-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
38-- if we use one array for each chunk. This is still significant to add
39-- pressure to GC.
41module Streamly.Internal.Memory.Array
42 (
43 Array
45 -- , defaultChunkSize
47 -- * Construction
49 -- Pure List APIs
50 , A.fromListN
51 , A.fromList
53 -- Stream Folds
54 , fromStreamN
55 , fromStream
57 -- Monadic APIs
58 -- , newArray
59 , A.writeN -- drop new
60 , A.write -- full buffer
61 -- , writeLastN -- drop old (ring buffer)
63 -- * Elimination
65 , A.toList
66 , toStream
67 , toStreamRev
68 , read
69 -- , readChunksOf
71 -- * Random Access
72 , length
73 , null
74 , last
75 -- , (!!)
76 , readIndex
77 -- , readIndices
78 -- , readRanges
80 -- , readFrom -- read from a given position to the end of file
81 -- , readFromRev -- read from a given position to the beginning of file
82 -- , readTo -- read from beginning up to the given position
83 -- , readToRev -- read from end to the given position in file
84 -- , readFromTo
85 -- , readFromThenTo
87 -- , readChunksOfFrom
88 -- , ...
90 -- , writeIndex
91 -- , writeFrom -- start writing at the given position
92 -- , writeFromRev
93 -- , writeTo -- write from beginning up to the given position
94 -- , writeToRev
95 -- , writeFromTo
96 -- , writeFromThenTo
97 --
98 -- , writeChunksOfFrom
99 -- , ...
101 , writeIndex
102 --, writeIndices
103 --, writeRanges
105 -- -- * Search
106 -- , bsearch
107 -- , bsearchIndex
108 -- , find
109 -- , findIndex
110 -- , findIndices
112 -- -- * In-pace mutation (for Mutable Array type)
113 -- , partitionBy
114 -- , shuffleBy
115 -- , foldtWith
116 -- , foldbWith
118 -- * Immutable Transformations
119 , streamTransform
121 -- * Folding Arrays
122 , streamFold
123 , fold
124 )
125where
127import Control.Monad.IO.Class (MonadIO(..))
128-- import Data.Functor.Identity (Identity)
129import Foreign.ForeignPtr (withForeignPtr, touchForeignPtr)
130import Foreign.Ptr (plusPtr)
131import Foreign.Storable (Storable(..))
132import Prelude hiding (length, null, last, map, (!!), read, concat)
134import GHC.ForeignPtr (ForeignPtr(..))
135import GHC.Ptr (Ptr(..))
137import Streamly.Internal.Data.Fold.Types (Fold(..))
138import Streamly.Internal.Data.Unfold.Types (Unfold(..))
139import Streamly.Internal.Memory.Array.Types (Array(..), length)
140import Streamly.Streams.Serial (SerialT)
141import Streamly.Streams.StreamK.Type (IsStream)
143import qualified Streamly.Internal.Memory.Array.Types as A
144import qualified Streamly.Streams.Prelude as P
145import qualified Streamly.Streams.Serial as Serial
146import qualified Streamly.Streams.StreamD as D
147import qualified Streamly.Streams.StreamK as K
149-------------------------------------------------------------------------------
150-- Construction
151-------------------------------------------------------------------------------
153{-
154-- | Create a new uninitialized array of given length.
155--
156-- @since 0.7.0
157newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
158newArray len = undefined
159-}
161-- | Create an 'Array' from the first N elements of a stream. The array is
162-- allocated to size N, if the stream terminates before N elements then the
163-- array may hold less than N elements.
164--
165-- /Internal/
166{-# INLINE fromStreamN #-}
167fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
168fromStreamN n m = do
169 if n < 0 then error "writeN: negative write count specified" else return ()
170 A.fromStreamDN n $ D.toStreamD m
172-- | Create an 'Array' from a stream. This is useful when we want to create a
173-- single array from a stream of unknown size. 'writeN' is at least twice
174-- as efficient when the size is already known.
175--
176-- Note that if the input stream is too large memory allocation for the array
177-- may fail. When the stream size is not known, `arraysOf` followed by
178-- processing of indvidual arrays in the resulting stream should be preferred.
179--
180-- /Internal/
181{-# INLINE fromStream #-}
182fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
183fromStream = P.runFold A.write
184-- write m = A.fromStreamD $ D.toStreamD m
186-------------------------------------------------------------------------------
187-- Elimination
188-------------------------------------------------------------------------------
190-- | Convert an 'Array' into a stream.
191--
192-- /Internal/
193{-# INLINE_EARLY toStream #-}
194toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
195toStream = D.fromStreamD . A.toStreamD
196-- XXX add fallback to StreamK rule
197-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
198-- forall a. S.readK (read a) = K.fromArray a #-}
200-- | Convert an 'Array' into a stream in reverse order.
201--
202-- /Internal/
203{-# INLINE_EARLY toStreamRev #-}
204toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
205toStreamRev = D.fromStreamD . A.toStreamDRev
206-- XXX add fallback to StreamK rule
207-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
208-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
210data ReadUState a = ReadUState
211 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
212 {-# UNPACK #-} !(Ptr a) -- current pointer
214-- | Unfold an array into a stream.
215--
216-- @since 0.7.0
217{-# INLINE_NORMAL read #-}
218read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
219read = Unfold step inject
220 where
222 inject (Array (ForeignPtr start contents) (Ptr end) _) =
223 return $ ReadUState (ForeignPtr end contents) (Ptr start)
225 {-# INLINE_LATE step #-}
226 step (ReadUState fp@(ForeignPtr end _) p) | p == (Ptr end) =
227 let x = A.unsafeInlineIO $ touchForeignPtr fp
228 in x `seq` return D.Stop
229 step (ReadUState fp p) = do
230 -- unsafeInlineIO allows us to run this in Identity monad for pure
231 -- toList/foldr case which makes them much faster due to not
232 -- accumulating the list and fusing better with the pure consumers.
233 --
234 -- This should be safe as the array contents are guaranteed to be
235 -- evaluated/written to before we peek at them.
236 let !x = A.unsafeInlineIO $ peek p
237 return $ D.Yield x
238 (ReadUState fp (p `plusPtr` (sizeOf (undefined :: a))))
240-- | > null arr = length arr == 0
241--
242-- /Internal/
243{-# INLINE null #-}
244null :: Storable a => Array a -> Bool
245null arr = length arr == 0
247-- | > last arr = readIndex arr (length arr - 1)
248--
249-- /Internal/
250{-# INLINE last #-}
251last :: Storable a => Array a -> Maybe a
252last arr = readIndex arr (length arr - 1)
254-------------------------------------------------------------------------------
255-- Random Access
256-------------------------------------------------------------------------------
258-------------------------------------------------------------------------------
259-- Searching
260-------------------------------------------------------------------------------
262{-
263-- | Perform a binary search in the array to find an element.
264bsearch :: a -> Array a -> Maybe Bool
265bsearch = undefined
267-- | Perform a binary search in the array to find an element index.
268{-# INLINE elemIndex #-}
269bsearchIndex :: a -> Array a -> Maybe Int
270bsearchIndex elem arr = undefined
272-- find/findIndex etc can potentially be implemented more efficiently on arrays
273-- compared to streams by using SIMD instructions.
275find :: (a -> Bool) -> Array a -> Bool
276find = undefined
278findIndex :: (a -> Bool) -> Array a -> Maybe Int
279findIndex = undefined
281findIndices :: (a -> Bool) -> Array a -> Array Int
282findIndices = undefined
283-}
285-------------------------------------------------------------------------------
286-- Folds
287-------------------------------------------------------------------------------
289-- XXX We can potentially use SIMD instructions on arrays to fold faster.
291-------------------------------------------------------------------------------
292-- Slice and splice
293-------------------------------------------------------------------------------
295{-
296slice :: Int -> Int -> Array a
297slice begin end arr = undefined
299splitAt :: Int -> Array a -> (Array a, Array a)
300splitAt i arr = undefined
302-- XXX This operation can be performed efficiently via streams.
303-- | Append two arrays together to create a single array.
304splice :: Array a -> Array a -> Array a
305splice arr1 arr2 = undefined
307-------------------------------------------------------------------------------
308-- In-place mutation APIs
309-------------------------------------------------------------------------------
311-- | Partition an array into two halves using a partitioning predicate. The
312-- first half retains values where the predicate is 'False' and the second half
313-- retains values where the predicate is 'True'.
314{-# INLINE partitionBy #-}
315partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
316partitionBy f arr = undefined
318-- | Shuffle corresponding elements from two arrays using a shuffle function.
319-- If the shuffle function returns 'False' then do nothing otherwise swap the
320-- elements. This can be used in a bottom up fold to shuffle or reorder the
321-- elements.
322shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
323shuffleBy f arr1 arr2 = undefined
325-- XXX we can also make the folds partial by stopping at a certain level.
326--
327-- | Perform a top down hierarchical recursive partitioning fold of items in
328-- the container using the given function as the partition function.
329--
330-- This will perform a quick sort if the partition function is
331-- 'partitionBy (< pivot)'.
332--
333-- @since 0.7.0
334{-# INLINABLE foldtWith #-}
335foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
336foldtWith level f = undefined
338-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
339-- indicates the level in the tree where the fold would stop.
340--
341-- This will perform a random shuffle if the shuffle function is random.
342-- If we stop at level 0 and repeatedly apply the function then we can do a
343-- bubble sort.
344foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
345foldbWith level f = undefined
346-}
348-- XXX consider the bulk update/accumulation/permutation APIs from vector.
350-------------------------------------------------------------------------------
351-- Random reads and writes
352-------------------------------------------------------------------------------
354-- | /O(1)/ Lookup the element at the given index, starting from 0.
355--
356-- /Internal/
357{-# INLINE readIndex #-}
358readIndex :: Storable a => Array a -> Int -> Maybe a
359readIndex arr i =
360 if i < 0 || i > length arr - 1
361 then Nothing
362 else A.unsafeInlineIO $
363 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
365{-
366-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
367-- at index @i@ and reading up to @count@ elements in the forward direction
368-- ending at the index @i + count - 1@.
369--
370-- @since 0.7.0
371{-# INLINE readSlice #-}
372readSlice :: (IsStream t, Monad m, Storable a)
373 => Array a -> Int -> Int -> t m a
374readSlice arr i len = undefined
376-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
377-- index @i@ and reading up to @count@ elements in the reverse direction ending
378-- at the index @i - count + 1@.
379--
380-- @since 0.7.0
381{-# INLINE readSliceRev #-}
382readSliceRev :: (IsStream t, Monad m, Storable a)
383 => Array a -> Int -> Int -> t m a
384readSliceRev arr i len = undefined
385-}
387-- | /O(1)/ Write the given element at the given index in the array.
388-- Performs in-place mutation of the array.
389--
390-- /Internal/
391{-# INLINE writeIndex #-}
392writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
393writeIndex arr i a = do
394 let maxIndex = length arr - 1
395 if i < 0
396 then error "writeIndex: negative array index"
397 else if i > maxIndex
398 then error $ "writeIndex: specified array index " ++ show i
399 ++ " is beyond the maximum index " ++ show maxIndex
400 else
401 liftIO $ withForeignPtr (aStart arr) $ \p ->
402 pokeElemOff p i a
404{-
405-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
406-- starting at index @i@ and writing up to @count@ elements in the forward
407-- direction ending at the index @i + count - 1@.
408--
409-- @since 0.7.0
410{-# INLINE writeSlice #-}
411writeSlice :: (IsStream t, Monad m, Storable a)
412 => Array a -> Int -> Int -> t m a -> m ()
413writeSlice arr i len s = undefined
415-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
416-- starting at index @i@ and writing up to @count@ elements in the reverse
417-- direction ending at the index @i - count + 1@.
418--
419-- @since 0.7.0
420{-# INLINE writeSliceRev #-}
421writeSliceRev :: (IsStream t, Monad m, Storable a)
422 => Array a -> Int -> Int -> t m a -> m ()
423writeSliceRev arr i len s = undefined
424-}
426-------------------------------------------------------------------------------
427-- Transform via stream operations
428-------------------------------------------------------------------------------
430-- for non-length changing operations we can use the original length for
431-- allocation. If we can predict the length then we can use the prediction for
432-- new allocation. Otherwise we can use a hint and adjust dynamically.
434{-
435-- | Transform an array into another array using a pipe transformation
436-- operation.
437--
438-- @since 0.7.0
439{-# INLINE runPipe #-}
440runPipe :: (MonadIO m, Storable a, Storable b)
441 => Pipe m a b -> Array a -> m (Array b)
442runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
443-}
445-- | Transform an array into another array using a stream transformation
446-- operation.
447--
448-- /Internal/
449{-# INLINE streamTransform #-}
450streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
451 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
452streamTransform f arr =
453 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
454 $ f (toStream arr)
456-- | Fold an array using a 'Fold'.
457--
458-- /Internal/
459{-# INLINE fold #-}
460fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
461fold f arr = P.runFold f $ (toStream arr :: Serial.SerialT m a)
463-- | Fold an array using a stream fold operation.
464--
465-- /Internal/
466{-# INLINE streamFold #-}
467streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
468streamFold f arr = f (toStream arr)