on e16a980 help sign in
470 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.writeNAligned
61 , A.write -- full buffer
62 -- , writeLastN -- drop old (ring buffer)
64 -- * Elimination
66 , A.toList
67 , toStream
68 , toStreamRev
69 , read
70 -- , readChunksOf
72 -- * Random Access
73 , length
74 , null
75 , last
76 -- , (!!)
77 , readIndex
78 , A.unsafeIndex
79 -- , readIndices
80 -- , readRanges
82 -- , readFrom -- read from a given position to the end of file
83 -- , readFromRev -- read from a given position to the beginning of file
84 -- , readTo -- read from beginning up to the given position
85 -- , readToRev -- read from end to the given position in file
86 -- , readFromTo
87 -- , readFromThenTo
89 -- , readChunksOfFrom
90 -- , ...
92 -- , writeIndex
93 -- , writeFrom -- start writing at the given position
94 -- , writeFromRev
95 -- , writeTo -- write from beginning up to the given position
96 -- , writeToRev
97 -- , writeFromTo
98 -- , writeFromThenTo
99 --
100 -- , writeChunksOfFrom
101 -- , ...
103 , writeIndex
104 --, writeIndices
105 --, writeRanges
107 -- -- * Search
108 -- , bsearch
109 -- , bsearchIndex
110 -- , find
111 -- , findIndex
112 -- , findIndices
114 -- -- * In-pace mutation (for Mutable Array type)
115 -- , partitionBy
116 -- , shuffleBy
117 -- , foldtWith
118 -- , foldbWith
120 -- * Immutable Transformations
121 , streamTransform
123 -- * Folding Arrays
124 , streamFold
125 , fold
126 )
127where
129import Control.Monad.IO.Class (MonadIO(..))
130-- import Data.Functor.Identity (Identity)
131import Foreign.ForeignPtr (withForeignPtr, touchForeignPtr)
132import Foreign.Ptr (plusPtr)
133import Foreign.Storable (Storable(..))
134import Prelude hiding (length, null, last, map, (!!), read, concat)
136import GHC.ForeignPtr (ForeignPtr(..))
137import GHC.Ptr (Ptr(..))
139import Streamly.Internal.Data.Fold.Types (Fold(..))
140import Streamly.Internal.Data.Unfold.Types (Unfold(..))
141import Streamly.Internal.Memory.Array.Types (Array(..), length)
142import Streamly.Streams.Serial (SerialT)
143import Streamly.Streams.StreamK.Type (IsStream)
145import qualified Streamly.Internal.Memory.Array.Types as A
146import qualified Streamly.Streams.Prelude as P
147import qualified Streamly.Streams.Serial as Serial
148import qualified Streamly.Streams.StreamD as D
149import qualified Streamly.Streams.StreamK as K
151-------------------------------------------------------------------------------
152-- Construction
153-------------------------------------------------------------------------------
155{-
156-- | Create a new uninitialized array of given length.
157--
158-- @since 0.7.0
159newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
160newArray len = undefined
161-}
163-- | Create an 'Array' from the first N elements of a stream. The array is
164-- allocated to size N, if the stream terminates before N elements then the
165-- array may hold less than N elements.
166--
167-- /Internal/
168{-# INLINE fromStreamN #-}
169fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
170fromStreamN n m = do
171 if n < 0 then error "writeN: negative write count specified" else return ()
172 A.fromStreamDN n $ D.toStreamD m
174-- | Create an 'Array' from a stream. This is useful when we want to create a
175-- single array from a stream of unknown size. 'writeN' is at least twice
176-- as efficient when the size is already known.
177--
178-- Note that if the input stream is too large memory allocation for the array
179-- may fail. When the stream size is not known, `arraysOf` followed by
180-- processing of indvidual arrays in the resulting stream should be preferred.
181--
182-- /Internal/
183{-# INLINE fromStream #-}
184fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
185fromStream = P.runFold A.write
186-- write m = A.fromStreamD $ D.toStreamD m
188-------------------------------------------------------------------------------
189-- Elimination
190-------------------------------------------------------------------------------
192-- | Convert an 'Array' into a stream.
193--
194-- /Internal/
195{-# INLINE_EARLY toStream #-}
196toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
197toStream = D.fromStreamD . A.toStreamD
198-- XXX add fallback to StreamK rule
199-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
200-- forall a. S.readK (read a) = K.fromArray a #-}
202-- | Convert an 'Array' into a stream in reverse order.
203--
204-- /Internal/
205{-# INLINE_EARLY toStreamRev #-}
206toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
207toStreamRev = D.fromStreamD . A.toStreamDRev
208-- XXX add fallback to StreamK rule
209-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
210-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
212data ReadUState a = ReadUState
213 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
214 {-# UNPACK #-} !(Ptr a) -- current pointer
216-- | Unfold an array into a stream.
217--
218-- @since 0.7.0
219{-# INLINE_NORMAL read #-}
220read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
221read = Unfold step inject
222 where
224 inject (Array (ForeignPtr start contents) (Ptr end) _) =
225 return $ ReadUState (ForeignPtr end contents) (Ptr start)
227 {-# INLINE_LATE step #-}
228 step (ReadUState fp@(ForeignPtr end _) p) | p == (Ptr end) =
229 let x = A.unsafeInlineIO $ touchForeignPtr fp
230 in x `seq` return D.Stop
231 step (ReadUState fp p) = do
232 -- unsafeInlineIO allows us to run this in Identity monad for pure
233 -- toList/foldr case which makes them much faster due to not
234 -- accumulating the list and fusing better with the pure consumers.
235 --
236 -- This should be safe as the array contents are guaranteed to be
237 -- evaluated/written to before we peek at them.
238 let !x = A.unsafeInlineIO $ peek p
239 return $ D.Yield x
240 (ReadUState fp (p `plusPtr` (sizeOf (undefined :: a))))
242-- | > null arr = length arr == 0
243--
244-- /Internal/
245{-# INLINE null #-}
246null :: Storable a => Array a -> Bool
247null arr = length arr == 0
249-- | > last arr = readIndex arr (length arr - 1)
250--
251-- /Internal/
252{-# INLINE last #-}
253last :: Storable a => Array a -> Maybe a
254last arr = readIndex arr (length arr - 1)
256-------------------------------------------------------------------------------
257-- Random Access
258-------------------------------------------------------------------------------
260-------------------------------------------------------------------------------
261-- Searching
262-------------------------------------------------------------------------------
264{-
265-- | Perform a binary search in the array to find an element.
266bsearch :: a -> Array a -> Maybe Bool
267bsearch = undefined
269-- | Perform a binary search in the array to find an element index.
270{-# INLINE elemIndex #-}
271bsearchIndex :: a -> Array a -> Maybe Int
272bsearchIndex elem arr = undefined
274-- find/findIndex etc can potentially be implemented more efficiently on arrays
275-- compared to streams by using SIMD instructions.
277find :: (a -> Bool) -> Array a -> Bool
278find = undefined
280findIndex :: (a -> Bool) -> Array a -> Maybe Int
281findIndex = undefined
283findIndices :: (a -> Bool) -> Array a -> Array Int
284findIndices = undefined
285-}
287-------------------------------------------------------------------------------
288-- Folds
289-------------------------------------------------------------------------------
291-- XXX We can potentially use SIMD instructions on arrays to fold faster.
293-------------------------------------------------------------------------------
294-- Slice and splice
295-------------------------------------------------------------------------------
297{-
298slice :: Int -> Int -> Array a
299slice begin end arr = undefined
301splitAt :: Int -> Array a -> (Array a, Array a)
302splitAt i arr = undefined
304-- XXX This operation can be performed efficiently via streams.
305-- | Append two arrays together to create a single array.
306splice :: Array a -> Array a -> Array a
307splice arr1 arr2 = undefined
309-------------------------------------------------------------------------------
310-- In-place mutation APIs
311-------------------------------------------------------------------------------
313-- | Partition an array into two halves using a partitioning predicate. The
314-- first half retains values where the predicate is 'False' and the second half
315-- retains values where the predicate is 'True'.
316{-# INLINE partitionBy #-}
317partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
318partitionBy f arr = undefined
320-- | Shuffle corresponding elements from two arrays using a shuffle function.
321-- If the shuffle function returns 'False' then do nothing otherwise swap the
322-- elements. This can be used in a bottom up fold to shuffle or reorder the
323-- elements.
324shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
325shuffleBy f arr1 arr2 = undefined
327-- XXX we can also make the folds partial by stopping at a certain level.
328--
329-- | Perform a top down hierarchical recursive partitioning fold of items in
330-- the container using the given function as the partition function.
331--
332-- This will perform a quick sort if the partition function is
333-- 'partitionBy (< pivot)'.
334--
335-- @since 0.7.0
336{-# INLINABLE foldtWith #-}
337foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
338foldtWith level f = undefined
340-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
341-- indicates the level in the tree where the fold would stop.
342--
343-- This will perform a random shuffle if the shuffle function is random.
344-- If we stop at level 0 and repeatedly apply the function then we can do a
345-- bubble sort.
346foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
347foldbWith level f = undefined
348-}
350-- XXX consider the bulk update/accumulation/permutation APIs from vector.
352-------------------------------------------------------------------------------
353-- Random reads and writes
354-------------------------------------------------------------------------------
356-- | /O(1)/ Lookup the element at the given index, starting from 0.
357--
358-- /Internal/
359{-# INLINE readIndex #-}
360readIndex :: Storable a => Array a -> Int -> Maybe a
361readIndex arr i =
362 if i < 0 || i > length arr - 1
363 then Nothing
364 else A.unsafeInlineIO $
365 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
367{-
368-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
369-- at index @i@ and reading up to @count@ elements in the forward direction
370-- ending at the index @i + count - 1@.
371--
372-- @since 0.7.0
373{-# INLINE readSlice #-}
374readSlice :: (IsStream t, Monad m, Storable a)
375 => Array a -> Int -> Int -> t m a
376readSlice arr i len = undefined
378-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
379-- index @i@ and reading up to @count@ elements in the reverse direction ending
380-- at the index @i - count + 1@.
381--
382-- @since 0.7.0
383{-# INLINE readSliceRev #-}
384readSliceRev :: (IsStream t, Monad m, Storable a)
385 => Array a -> Int -> Int -> t m a
386readSliceRev arr i len = undefined
387-}
389-- | /O(1)/ Write the given element at the given index in the array.
390-- Performs in-place mutation of the array.
391--
392-- /Internal/
393{-# INLINE writeIndex #-}
394writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
395writeIndex arr i a = do
396 let maxIndex = length arr - 1
397 if i < 0
398 then error "writeIndex: negative array index"
399 else if i > maxIndex
400 then error $ "writeIndex: specified array index " ++ show i
401 ++ " is beyond the maximum index " ++ show maxIndex
402 else
403 liftIO $ withForeignPtr (aStart arr) $ \p ->
404 pokeElemOff p i a
406{-
407-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
408-- starting at index @i@ and writing up to @count@ elements in the forward
409-- direction ending at the index @i + count - 1@.
410--
411-- @since 0.7.0
412{-# INLINE writeSlice #-}
413writeSlice :: (IsStream t, Monad m, Storable a)
414 => Array a -> Int -> Int -> t m a -> m ()
415writeSlice arr i len s = undefined
417-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
418-- starting at index @i@ and writing up to @count@ elements in the reverse
419-- direction ending at the index @i - count + 1@.
420--
421-- @since 0.7.0
422{-# INLINE writeSliceRev #-}
423writeSliceRev :: (IsStream t, Monad m, Storable a)
424 => Array a -> Int -> Int -> t m a -> m ()
425writeSliceRev arr i len s = undefined
426-}
428-------------------------------------------------------------------------------
429-- Transform via stream operations
430-------------------------------------------------------------------------------
432-- for non-length changing operations we can use the original length for
433-- allocation. If we can predict the length then we can use the prediction for
434-- new allocation. Otherwise we can use a hint and adjust dynamically.
436{-
437-- | Transform an array into another array using a pipe transformation
438-- operation.
439--
440-- @since 0.7.0
441{-# INLINE runPipe #-}
442runPipe :: (MonadIO m, Storable a, Storable b)
443 => Pipe m a b -> Array a -> m (Array b)
444runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
445-}
447-- | Transform an array into another array using a stream transformation
448-- operation.
449--
450-- /Internal/
451{-# INLINE streamTransform #-}
452streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
453 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
454streamTransform f arr =
455 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
456 $ f (toStream arr)
458-- | Fold an array using a 'Fold'.
459--
460-- /Internal/
461{-# INLINE fold #-}
462fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
463fold f arr = P.runFold f $ (toStream arr :: Serial.SerialT m a)
465-- | Fold an array using a stream fold operation.
466--
467-- /Internal/
468{-# INLINE streamFold #-}
469streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
470streamFold f arr = f (toStream arr)