on 33b00a6 help sign in
508 lines 17 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 , unsafeRead
71 -- , readChunksOf
73 -- * Random Access
74 , length
75 , null
76 , last
77 -- , (!!)
78 , readIndex
79 , A.unsafeIndex
80 -- , readIndices
81 -- , readRanges
83 -- , readFrom -- read from a given position to the end of file
84 -- , readFromRev -- read from a given position to the beginning of file
85 -- , readTo -- read from beginning up to the given position
86 -- , readToRev -- read from end to the given position in file
87 -- , readFromTo
88 -- , readFromThenTo
90 -- , readChunksOfFrom
91 -- , ...
93 -- , writeIndex
94 -- , writeFrom -- start writing at the given position
95 -- , writeFromRev
96 -- , writeTo -- write from beginning up to the given position
97 -- , writeToRev
98 -- , writeFromTo
99 -- , writeFromThenTo
100 --
101 -- , writeChunksOfFrom
102 -- , ...
104 , writeIndex
105 --, writeIndices
106 --, writeRanges
108 -- -- * Search
109 -- , bsearch
110 -- , bsearchIndex
111 -- , find
112 -- , findIndex
113 -- , findIndices
115 -- -- * In-pace mutation (for Mutable Array type)
116 -- , partitionBy
117 -- , shuffleBy
118 -- , foldtWith
119 -- , foldbWith
121 -- * Immutable Transformations
122 , streamTransform
124 -- * Folding Arrays
125 , streamFold
126 , fold
127 )
128where
130import Control.Monad.IO.Class (MonadIO(..))
131-- import Data.Functor.Identity (Identity)
132import Foreign.ForeignPtr (withForeignPtr, touchForeignPtr)
133import Foreign.Ptr (plusPtr)
134import Foreign.Storable (Storable(..))
135import Prelude hiding (length, null, last, map, (!!), read, concat)
137import GHC.ForeignPtr (ForeignPtr(..))
138import GHC.Ptr (Ptr(..))
139import GHC.Prim (touch#)
140import GHC.IO (IO(..))
142import Streamly.Internal.Data.Fold.Types (Fold(..))
143import Streamly.Internal.Data.Unfold.Types (Unfold(..))
144import Streamly.Internal.Memory.Array.Types (Array(..), length)
145import Streamly.Internal.Data.Stream.Serial (SerialT)
146import Streamly.Internal.Data.Stream.StreamK.Type (IsStream)
148import qualified Streamly.Internal.Memory.Array.Types as A
149import qualified Streamly.Internal.Data.Stream.Prelude as P
150import qualified Streamly.Internal.Data.Stream.Serial as Serial
151import qualified Streamly.Internal.Data.Stream.StreamD as D
152import qualified Streamly.Internal.Data.Stream.StreamK as K
154-------------------------------------------------------------------------------
155-- Construction
156-------------------------------------------------------------------------------
158{-
159-- | Create a new uninitialized array of given length.
160--
161-- @since 0.7.0
162newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
163newArray len = undefined
164-}
166-- | Create an 'Array' from the first N elements of a stream. The array is
167-- allocated to size N, if the stream terminates before N elements then the
168-- array may hold less than N elements.
169--
170-- /Internal/
171{-# INLINE fromStreamN #-}
172fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
173fromStreamN n m = do
174 if n < 0 then error "writeN: negative write count specified" else return ()
175 A.fromStreamDN n $ D.toStreamD m
177-- | Create an 'Array' from a stream. This is useful when we want to create a
178-- single array from a stream of unknown size. 'writeN' is at least twice
179-- as efficient when the size is already known.
180--
181-- Note that if the input stream is too large memory allocation for the array
182-- may fail. When the stream size is not known, `arraysOf` followed by
183-- processing of indvidual arrays in the resulting stream should be preferred.
184--
185-- /Internal/
186{-# INLINE fromStream #-}
187fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
188fromStream = P.runFold A.write
189-- write m = A.fromStreamD $ D.toStreamD m
191-------------------------------------------------------------------------------
192-- Elimination
193-------------------------------------------------------------------------------
195-- | Convert an 'Array' into a stream.
196--
197-- /Internal/
198{-# INLINE_EARLY toStream #-}
199toStream :: (Monad m, K.IsStream t, Storable a) => Array a -> t m a
200toStream = D.fromStreamD . A.toStreamD
201-- XXX add fallback to StreamK rule
202-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
203-- forall a. S.readK (read a) = K.fromArray a #-}
205-- | Convert an 'Array' into a stream in reverse order.
206--
207-- /Internal/
208{-# INLINE_EARLY toStreamRev #-}
209toStreamRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
210toStreamRev = D.fromStreamD . A.toStreamDRev
211-- XXX add fallback to StreamK rule
212-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
213-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
215data ReadUState a = ReadUState
216 {-# UNPACK #-} !(ForeignPtr a) -- foreign ptr with end of array pointer
217 {-# UNPACK #-} !(Ptr a) -- current pointer
219-- | Unfold an array into a stream.
220--
221-- @since 0.7.0
222{-# INLINE_NORMAL read #-}
223read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
224read = Unfold step inject
225 where
227 inject (Array (ForeignPtr start contents) (Ptr end) _) =
228 return $ ReadUState (ForeignPtr end contents) (Ptr start)
230 {-# INLINE_LATE step #-}
231 step (ReadUState fp@(ForeignPtr end _) p) | p == (Ptr end) =
232 let x = A.unsafeInlineIO $ touchForeignPtr fp
233 in x `seq` return D.Stop
234 step (ReadUState fp p) = do
235 -- unsafeInlineIO allows us to run this in Identity monad for pure
236 -- toList/foldr case which makes them much faster due to not
237 -- accumulating the list and fusing better with the pure consumers.
238 --
239 -- This should be safe as the array contents are guaranteed to be
240 -- evaluated/written to before we peek at them.
241 let !x = A.unsafeInlineIO $ peek p
242 return $ D.Yield x
243 (ReadUState fp (p `plusPtr` (sizeOf (undefined :: a))))
245-- | Unfold an array into a stream, does not check the end of the array, the
246-- user is responsible for terminating the stream within the array bounds. For
247-- high performance application where the end condition can be determined by
248-- a terminating fold.
249--
250-- Written in the hope that it may be faster than "read", however, in the case
251-- for which this was written, "read" proves to be faster even though the core
252-- generated with unsafeRead looks simpler.
253--
254-- /Internal/
255--
256{-# INLINE_NORMAL unsafeRead #-}
257unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
258unsafeRead = Unfold step inject
259 where
261 inject (Array fp _ _) = return fp
263 {-# INLINE_LATE step #-}
264 step (ForeignPtr p contents) = do
265 -- unsafeInlineIO allows us to run this in Identity monad for pure
266 -- toList/foldr case which makes them much faster due to not
267 -- accumulating the list and fusing better with the pure consumers.
268 --
269 -- This should be safe as the array contents are guaranteed to be
270 -- evaluated/written to before we peek at them.
271 let !x = A.unsafeInlineIO $ do
272 r <- peek (Ptr p)
273 touch contents
274 return r
275 let !(Ptr p1) = Ptr p `plusPtr` (sizeOf (undefined :: a))
276 return $ D.Yield x (ForeignPtr p1 contents)
278 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
280-- | > null arr = length arr == 0
281--
282-- /Internal/
283{-# INLINE null #-}
284null :: Storable a => Array a -> Bool
285null arr = length arr == 0
287-- | > last arr = readIndex arr (length arr - 1)
288--
289-- /Internal/
290{-# INLINE last #-}
291last :: Storable a => Array a -> Maybe a
292last arr = readIndex arr (length arr - 1)
294-------------------------------------------------------------------------------
295-- Random Access
296-------------------------------------------------------------------------------
298-------------------------------------------------------------------------------
299-- Searching
300-------------------------------------------------------------------------------
302{-
303-- | Perform a binary search in the array to find an element.
304bsearch :: a -> Array a -> Maybe Bool
305bsearch = undefined
307-- | Perform a binary search in the array to find an element index.
308{-# INLINE elemIndex #-}
309bsearchIndex :: a -> Array a -> Maybe Int
310bsearchIndex elem arr = undefined
312-- find/findIndex etc can potentially be implemented more efficiently on arrays
313-- compared to streams by using SIMD instructions.
315find :: (a -> Bool) -> Array a -> Bool
316find = undefined
318findIndex :: (a -> Bool) -> Array a -> Maybe Int
319findIndex = undefined
321findIndices :: (a -> Bool) -> Array a -> Array Int
322findIndices = undefined
323-}
325-------------------------------------------------------------------------------
326-- Folds
327-------------------------------------------------------------------------------
329-- XXX We can potentially use SIMD instructions on arrays to fold faster.
331-------------------------------------------------------------------------------
332-- Slice and splice
333-------------------------------------------------------------------------------
335{-
336slice :: Int -> Int -> Array a
337slice begin end arr = undefined
339splitAt :: Int -> Array a -> (Array a, Array a)
340splitAt i arr = undefined
342-- XXX This operation can be performed efficiently via streams.
343-- | Append two arrays together to create a single array.
344splice :: Array a -> Array a -> Array a
345splice arr1 arr2 = undefined
347-------------------------------------------------------------------------------
348-- In-place mutation APIs
349-------------------------------------------------------------------------------
351-- | Partition an array into two halves using a partitioning predicate. The
352-- first half retains values where the predicate is 'False' and the second half
353-- retains values where the predicate is 'True'.
354{-# INLINE partitionBy #-}
355partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
356partitionBy f arr = undefined
358-- | Shuffle corresponding elements from two arrays using a shuffle function.
359-- If the shuffle function returns 'False' then do nothing otherwise swap the
360-- elements. This can be used in a bottom up fold to shuffle or reorder the
361-- elements.
362shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
363shuffleBy f arr1 arr2 = undefined
365-- XXX we can also make the folds partial by stopping at a certain level.
366--
367-- | Perform a top down hierarchical recursive partitioning fold of items in
368-- the container using the given function as the partition function.
369--
370-- This will perform a quick sort if the partition function is
371-- 'partitionBy (< pivot)'.
372--
373-- @since 0.7.0
374{-# INLINABLE foldtWith #-}
375foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
376foldtWith level f = undefined
378-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
379-- indicates the level in the tree where the fold would stop.
380--
381-- This will perform a random shuffle if the shuffle function is random.
382-- If we stop at level 0 and repeatedly apply the function then we can do a
383-- bubble sort.
384foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
385foldbWith level f = undefined
386-}
388-- XXX consider the bulk update/accumulation/permutation APIs from vector.
390-------------------------------------------------------------------------------
391-- Random reads and writes
392-------------------------------------------------------------------------------
394-- | /O(1)/ Lookup the element at the given index, starting from 0.
395--
396-- /Internal/
397{-# INLINE readIndex #-}
398readIndex :: Storable a => Array a -> Int -> Maybe a
399readIndex arr i =
400 if i < 0 || i > length arr - 1
401 then Nothing
402 else A.unsafeInlineIO $
403 withForeignPtr (aStart arr) $ \p -> fmap Just $ peekElemOff p i
405{-
406-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
407-- at index @i@ and reading up to @count@ elements in the forward direction
408-- ending at the index @i + count - 1@.
409--
410-- @since 0.7.0
411{-# INLINE readSlice #-}
412readSlice :: (IsStream t, Monad m, Storable a)
413 => Array a -> Int -> Int -> t m a
414readSlice arr i len = undefined
416-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
417-- index @i@ and reading up to @count@ elements in the reverse direction ending
418-- at the index @i - count + 1@.
419--
420-- @since 0.7.0
421{-# INLINE readSliceRev #-}
422readSliceRev :: (IsStream t, Monad m, Storable a)
423 => Array a -> Int -> Int -> t m a
424readSliceRev arr i len = undefined
425-}
427-- | /O(1)/ Write the given element at the given index in the array.
428-- Performs in-place mutation of the array.
429--
430-- /Internal/
431{-# INLINE writeIndex #-}
432writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
433writeIndex arr i a = do
434 let maxIndex = length arr - 1
435 if i < 0
436 then error "writeIndex: negative array index"
437 else if i > maxIndex
438 then error $ "writeIndex: specified array index " ++ show i
439 ++ " is beyond the maximum index " ++ show maxIndex
440 else
441 liftIO $ withForeignPtr (aStart arr) $ \p ->
442 pokeElemOff p i a
444{-
445-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
446-- starting at index @i@ and writing up to @count@ elements in the forward
447-- direction ending at the index @i + count - 1@.
448--
449-- @since 0.7.0
450{-# INLINE writeSlice #-}
451writeSlice :: (IsStream t, Monad m, Storable a)
452 => Array a -> Int -> Int -> t m a -> m ()
453writeSlice arr i len s = undefined
455-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
456-- starting at index @i@ and writing up to @count@ elements in the reverse
457-- direction ending at the index @i - count + 1@.
458--
459-- @since 0.7.0
460{-# INLINE writeSliceRev #-}
461writeSliceRev :: (IsStream t, Monad m, Storable a)
462 => Array a -> Int -> Int -> t m a -> m ()
463writeSliceRev arr i len s = undefined
464-}
466-------------------------------------------------------------------------------
467-- Transform via stream operations
468-------------------------------------------------------------------------------
470-- for non-length changing operations we can use the original length for
471-- allocation. If we can predict the length then we can use the prediction for
472-- new allocation. Otherwise we can use a hint and adjust dynamically.
474{-
475-- | Transform an array into another array using a pipe transformation
476-- operation.
477--
478-- @since 0.7.0
479{-# INLINE runPipe #-}
480runPipe :: (MonadIO m, Storable a, Storable b)
481 => Pipe m a b -> Array a -> m (Array b)
482runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
483-}
485-- | Transform an array into another array using a stream transformation
486-- operation.
487--
488-- /Internal/
489{-# INLINE streamTransform #-}
490streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
491 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
492streamTransform f arr =
493 P.runFold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
494 $ f (toStream arr)
496-- | Fold an array using a 'Fold'.
497--
498-- /Internal/
499{-# INLINE fold #-}
500fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
501fold f arr = P.runFold f $ (toStream arr :: Serial.SerialT m a)
503-- | Fold an array using a stream fold operation.
504--
505-- /Internal/
506{-# INLINE streamFold #-}
507streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
508streamFold f arr = f (toStream arr)