on d462530 help sign in
503 lines 19 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.Mem.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-- Arrays are the computing duals of streams. Streams are good at sequential
20-- access and immutable transformations of in-transit data whereas arrays are
21-- good at random access and in-place transformations of buffered data. Unlike
22-- streams which are potentially infinite, arrays are necessarily /finite/.
23-- Arrays can be used as an efficient interface between streams and external
24-- storage systems like memory, files and network. Streams and arrays complete
25-- each other to provide a general purpose computing system. The design of
26-- streamly as a general purpose computing framework is centered around these
27-- two fundamental aspects of computing and storage.
28--
29-- Even though the implementation allows for in-place mutation, the current
30-- implementation of arrays is immutable. Arrays are of fixed size. The size of
31-- an array is fixed at creation and cannot be changed later without copying.
32-- Arrays are chunks of memory that hold a sequence of 'Storable' values of a
33-- given type. They are designed to store serializable data, they cannot store
34-- non-serializable data like functions, this is reflected by the 'Storable'
35-- constraint. For efficient buffering of data, arrays use pinned memory and
36-- therefore can hold arbitrary number of elements with a single movable
37-- pointer visible to GC, therefore, adding no pressure to GC. Moreover,
38-- pinned memory allows communication with foreign consumers and producers
39-- (e.g. file or network IO) without copying the data.
40--
41-- By design, there are no transformation operations provided in this module,
42-- only stream conversion and IO routines are provided. An array is purely a
43-- data store, therefore, it is not a 'Functor'. Arrays can be operated upon
44-- /efficiently/ by converting them into a stream, applying the desired
45-- transformations on the stream and then converting it back to an array.
46-- 'Foldable' instance is not provided because the implementation would be much
47-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
48-- instances are deliberately not provided to avoid misuse; concatenating
49-- arrays using binary operations can be highly inefficient. Instead, use
50-- 'spliceArrays' to concatenate N arrays at once.
51--
52-- To summarize:
53--
54-- * Arrays are finite and fixed in size
55-- * provide /O(1)/ access to elements
56-- * store only data and not functions
57-- * provide efficient IO interfacing
58--
59-- 'ByteString' data type from the 'bytestring' package and the 'Text' data
60-- type from the 'text' package are just special cases of arrays. 'ByteString'
61-- is equivalent to @Array Word8@ and 'Text' is equivalent to a @utf16@ encoded
62-- @Array Word8@. All the 'bytestring' and 'text' operations can be performed
63-- on arrays with equivalent or better performance by converting them to and
64-- from streams.
65--
66-- This module is designed to be imported qualified:
67--
68-- > import qualified Streamly.Array as A
70-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
71-- single byte) are only as good as holding those elements in a Haskell list.
72-- However, small arrays can be compacted into large ones to reduce the
73-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
74-- if we use one array for each chunk. This is still significant to add
75-- pressure to GC. However, we can create arrays of arrays (trees) to scale to
76-- arbitrarily large amounts of memory but still using small chunks of
77-- contiguous memory.
79module Streamly.Mem.Array
80 (
81 Array
83 -- , defaultChunkSize
85 -- * Construction
86 -- | When performance matters, the fastest way to generate an array is
87 -- 'writeN'. For regular use, 'IsList' and 'IsString' instances can be
88 -- used to conveniently construct arrays from literal values.
89 -- 'OverloadedLists' extension or 'fromList' can be used to construct an
90 -- array from a list literal. Similarly, 'OverloadedStrings' extension or
91 -- 'fromList' can be used to construct an array from a string literal.
93 -- Pure List APIs
94 , A.fromListN
95 , A.fromList
97 -- Monadic APIs
98 -- , newArray
99 , writeN
100 , write
102 -- Stream Folds
103 , A.toArrayN
104 -- , toArrays
105 , toArray
107 -- * Elimination
108 -- 'GHC.Exts.toList' from "GHC.Exts" can be used to convert an array to a
109 -- list.
111 , A.toList
112 , A.read
113 , readRev
115 -- * Random Access
116 , length
117 -- , (!!)
119 , readIndex
120 {-
121 , readSlice
122 , readSliceRev
123 -}
125 -- , writeIndex
126 {-
127 , writeSlice
128 , writeSliceRev
129 -}
131 -- * Immutable Transformations
132 , runTransform
134 -- * Folding Arrays
135 -- , runStreamFold
136 , runFold
137 )
138where
140import Control.Monad (when)
141import Control.Monad.IO.Class (MonadIO(..))
142-- import Data.Functor.Identity (Identity)
143import Foreign.ForeignPtr (withForeignPtr)
144import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
145import Foreign.Ptr (minusPtr, plusPtr)
146import Foreign.Storable (Storable(..))
147import Prelude hiding (length, null, last, map, (!!), read)
149import Streamly.Mem.Array.Types (Array(..), length)
150import Streamly.Streams.Serial (SerialT)
151import Streamly.Streams.StreamK.Type (IsStream)
152import Streamly.Fold.Types (Fold(..))
154import qualified Streamly.Mem.Array.Types as A
155import qualified Streamly.Streams.Prelude as P
156import qualified Streamly.Streams.Serial as Serial
157import qualified Streamly.Streams.StreamD as D
159-------------------------------------------------------------------------------
160-- Construction
161-------------------------------------------------------------------------------
163{-
164-- | Create a new uninitialized array of given length.
165--
166-- @since 0.7.0
167newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
168newArray len = undefined
169-}
171-- | Create an 'Array' from the first N elements of a stream. The array is
172-- allocated to size N, if the stream terminates before N elements then the
173-- array may hold less than N elements.
174--
175-- @since 0.7.0
176{-# INLINE writeN #-}
177writeN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
178writeN n m = do
179 if n < 0 then error "writeN: negative write count specified" else return ()
180 A.fromStreamDN n $ D.toStreamD m
182-------------------------------------------------------------------------------
183-- Elimination
184-------------------------------------------------------------------------------
186-- | Convert an 'Array' into a stream in reverse order.
187--
188-- @since 0.7.0
189{-# INLINE_EARLY readRev #-}
190readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
191readRev = D.fromStreamD . A.toStreamDRev
192-- XXX add fallback to StreamK rule
193-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
194-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
196{-# INLINE _null #-}
197_null :: Storable a => Array a -> Bool
198_null arr = length arr == 0
200{-# INLINE _last #-}
201_last :: (MonadIO m, Storable a) => Array a -> m (Maybe a)
202_last arr = readIndex arr (length arr - 1)
204-------------------------------------------------------------------------------
205-- Random Access
206-------------------------------------------------------------------------------
208-------------------------------------------------------------------------------
209-- Searching
210-------------------------------------------------------------------------------
212{-
213-- | Perform a binary search in the array to find an element.
214bsearch :: a -> Array a -> Maybe Bool
215bsearch = undefined
217-- | Perform a binary search in the array to find an element index.
218{-# INLINE elemIndex #-}
219bsearchIndex :: a -> Array a -> Maybe Int
220bsearchIndex elem arr = undefined
222-- find/findIndex etc can potentially be implemented more efficiently on arrays
223-- compared to streams by using SIMD instructions.
225find :: (a -> Bool) -> Array a -> Bool
226find = undefined
228findIndex :: (a -> Bool) -> Array a -> Maybe Int
229findIndex = undefined
231findIndices :: (a -> Bool) -> Array a -> Array Int
232findIndices = undefined
233-}
235-------------------------------------------------------------------------------
236-- Folds
237-------------------------------------------------------------------------------
239-- XXX We can potentially use SIMD instructions on arrays to fold faster.
241-------------------------------------------------------------------------------
242-- Slice and splice
243-------------------------------------------------------------------------------
245{-
246slice :: Int -> Int -> Array a
247slice begin end arr = undefined
249splitAt :: Int -> Array a -> (Array a, Array a)
250splitAt i arr = undefined
252-- XXX This operation can be performed efficiently via streams.
253-- | Append two arrays together to create a single array.
254splice :: Array a -> Array a -> Array a
255splice arr1 arr2 = undefined
257-------------------------------------------------------------------------------
258-- In-place mutation APIs
259-------------------------------------------------------------------------------
261-- | Partition an array into two halves using a partitioning predicate. The
262-- first half retains values where the predicate is 'False' and the second half
263-- retains values where the predicate is 'True'.
264{-# INLINE partitionBy #-}
265partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
266partitionBy f arr = undefined
268-- | Shuffle corresponding elements from two arrays using a shuffle function.
269-- If the shuffle function returns 'False' then do nothing otherwise swap the
270-- elements. This can be used in a bottom up fold to shuffle or reorder the
271-- elements.
272shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
273shuffleBy f arr1 arr2 = undefined
275-- XXX we can also make the folds partial by stopping at a certain level.
276--
277-- | Perform a top down hierarchical recursive partitioning fold of items in
278-- the container using the given function as the partition function.
279--
280-- This will perform a quick sort if the partition function is
281-- 'partitionBy (< pivot)'.
282--
283-- @since 0.7.0
284{-# INLINABLE foldtWith #-}
285foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
286foldtWith level f = undefined
288-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
289-- indicates the level in the tree where the fold would stop.
290--
291-- This will perform a random shuffle if the shuffle function is random.
292-- If we stop at level 0 and repeatedly apply the function then we can do a
293-- bubble sort.
294foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
295foldbWith level f = undefined
296-}
298-- XXX consider the bulk update/accumulation/permutation APIs from vector.
300-------------------------------------------------------------------------------
301-- Random reads and writes
302-------------------------------------------------------------------------------
304-- | /O(1)/ Lookup the element at the given index.
305--
306-- @since 0.7.0
307{-# INLINE readIndex #-}
308readIndex :: (MonadIO m, Storable a) => Array a -> Int -> m (Maybe a)
309readIndex arr i =
310 if i < 0 || i > length arr - 1
311 then return Nothing
312 else liftIO $ withForeignPtr (aStart arr) $ \p ->
313 fmap Just $ peekElemOff p i
315{-
316-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
317-- at index @i@ and reading up to @count@ elements in the forward direction
318-- ending at the index @i + count - 1@.
319--
320-- @since 0.7.0
321{-# INLINE readSlice #-}
322readSlice :: (IsStream t, Monad m, Storable a)
323 => Array a -> Int -> Int -> t m a
324readSlice arr i len = undefined
326-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
327-- index @i@ and reading up to @count@ elements in the reverse direction ending
328-- at the index @i - count + 1@.
329--
330-- @since 0.7.0
331{-# INLINE readSliceRev #-}
332readSliceRev :: (IsStream t, Monad m, Storable a)
333 => Array a -> Int -> Int -> t m a
334readSliceRev arr i len = undefined
335-}
337-- | /O(1)/ Write the given element at the given index in the array.
338-- Performs in-place mutation of the array.
339--
340-- @since 0.7.0
341{-# INLINE _writeIndex #-}
342_writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
343_writeIndex arr i a = do
344 let maxIndex = length arr - 1
345 if i < 0
346 then error "writeIndex: negative array index"
347 else if i > maxIndex
348 then error $ "writeIndex: specified array index " ++ show i
349 ++ " is beyond the maximum index " ++ show maxIndex
350 else
351 liftIO $ withForeignPtr (aStart arr) $ \p ->
352 pokeElemOff p i a
354{-
355-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
356-- starting at index @i@ and writing up to @count@ elements in the forward
357-- direction ending at the index @i + count - 1@.
358--
359-- @since 0.7.0
360{-# INLINE writeSlice #-}
361writeSlice :: (IsStream t, Monad m, Storable a)
362 => Array a -> Int -> Int -> t m a -> m ()
363writeSlice arr i len s = undefined
365-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
366-- starting at index @i@ and writing up to @count@ elements in the reverse
367-- direction ending at the index @i - count + 1@.
368--
369-- @since 0.7.0
370{-# INLINE writeSliceRev #-}
371writeSliceRev :: (IsStream t, Monad m, Storable a)
372 => Array a -> Int -> Int -> t m a -> m ()
373writeSliceRev arr i len s = undefined
374-}
376-------------------------------------------------------------------------------
377-- Streams of Arrays
378-------------------------------------------------------------------------------
380-- exponentially increasing sizes of the chunks upto the max limit.
381-- XXX this will be easier to implement with parsers/terminating folds
382-- With this we should be able to reduce the number of chunks/allocations.
383-- The reallocation/copy based toArray can also be implemented using this.
384--
385{-
386{-# INLINE toArraysInRange #-}
387toArraysInRange :: (IsStream t, MonadIO m, Storable a)
388 => Int -> Int -> Fold m (Array a) b -> Fold m a b
389toArraysInRange low high (Fold step initial extract) =
390-}
392{-
393-- | Fold the input to a pure buffered stream (List) of arrays.
394{-# INLINE _toArraysOf #-}
395_toArraysOf :: (MonadIO m, Storable a)
396 => Int -> Fold m a (SerialT Identity (Array a))
397_toArraysOf n = FL.lchunksOf n (A.toArrayN n) FL.toStream
398-}
400-- XXX The realloc based implementation needs to make one extra copy if we use
401-- shrinkToFit. On the other hand, the stream of arrays implementation may
402-- buffer the array chunk pointers in memory but it does not have to shrink as
403-- we know the exact size in the end. However, memory copying does not seems to
404-- be as expensive as the allocations. Therefore, we need to reduce the number
405-- of allocations instead. Also, the size of allocations matters, right sizing
406-- an allocation even at the cost of copying sems to help. Should be measured
407-- on a big stream with heavy calls to toArray to see the effect.
408--
409-- XXX check if GHC's memory allocator is efficient enough. We can try the C
410-- malloc to compare against.
412{-# INLINE_NORMAL toArrayMinChunk #-}
413toArrayMinChunk :: forall m a. (MonadIO m, Storable a)
414 => Int -> Fold m a (Array a)
415-- toArrayMinChunk n = FL.mapM spliceArrays $ toArraysOf n
416toArrayMinChunk elemCount = Fold step initial extract
418 where
420 insertElem (Array start end bound) x = do
421 liftIO $ poke end x
422 return $ Array start (end `plusPtr` sizeOf (undefined :: a)) bound
424 initial = do
425 when (elemCount < 0) $ error "toArrayMinChunk: elemCount is negative"
426 liftIO $ A.newArray elemCount
427 step arr@(Array start end bound) x | end == bound = do
428 let p = unsafeForeignPtrToPtr start
429 oldSize = end `minusPtr` p
430 newSize = max (oldSize * 2) 1
431 arr1 <- liftIO $ A.realloc newSize arr
432 insertElem arr1 x
433 step arr x = insertElem arr x
434 extract = liftIO . A.shrinkToFit
436-- | Fold the whole input to a single array.
437--
438-- /Caution! Do not use this on infinite streams./
439--
440-- @since 0.7.0
441{-# INLINE toArray #-}
442toArray :: forall m a. (MonadIO m, Storable a) => Fold m a (Array a)
443toArray =
444 toArrayMinChunk (A.bytesToCount (undefined :: a) (A.mkChunkSize 1024))
446-- | Create an 'Array' from a stream. This is useful when we want to create a
447-- single array from a stream of unknown size. 'writeN' is at least twice
448-- as efficient when the size is already known.
449--
450-- Note that if the input stream is too large memory allocation for the array
451-- may fail. When the stream size is not known, `arraysOf` followed by
452-- processing of indvidual arrays in the resulting stream should be preferred.
453--
454{-# INLINE write #-}
455write :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
456write = P.runFold toArray
457-- write m = A.fromStreamD $ D.toStreamD m
459-- XXX efficiently compare two streams of arrays. Two streams can have chunks
460-- of different sizes, we can handle that in the stream comparison abstraction.
461-- This could be useful e.g. to fast compare whether two files differ.
463-------------------------------------------------------------------------------
464-- Transform via stream operations
465-------------------------------------------------------------------------------
467-- for non-length changing operations we can use the original length for
468-- allocation. If we can predict the length then we can use the prediction for
469-- new allocation. Otherwise we can use a hint and adjust dynamically.
471{-
472-- | Transform an array into another array using a pipe transformation
473-- operation.
474--
475-- @since 0.7.0
476{-# INLINE runPipe #-}
477runPipe :: (MonadIO m, Storable a, Storable b)
478 => Pipe m a b -> Array a -> m (Array b)
479runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
480-}
482-- | Transform an array into another array using a stream transformation
483-- operation.
484--
485-- @since 0.7.0
486{-# INLINE runTransform #-}
487runTransform :: (MonadIO m, Storable a, Storable b)
488 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
489runTransform f arr = P.runFold (toArrayMinChunk (length arr)) $ f (A.read arr)
491-- | Fold an array using a 'Fold'.
492--
493-- @since 0.7.0
494{-# INLINE runFold #-}
495runFold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
496runFold f arr = P.runFold f $ (A.read arr :: Serial.SerialT m a)
498-- | Fold an array using a stream fold operation.
499--
500-- @since 0.7.0
501{-# INLINE _runStreamFold #-}
502_runStreamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
503_runStreamFold f arr = f (A.read arr)