on 3ce574a help sign in
428 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.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, immutable transformations of in-transit data whereas arrays are good
21-- at random access, in-place transformations of buffered data. Unlike streams
22-- which are potentially infinite, arrays are necessarily /finite/. Arrays can
23-- be used as an efficient interface between streams and external storage
24-- systems like memory, files and network. Streams and arrays complete each
25-- other to provide a general purpose computing system. The design of streamly
26-- as a general purpose computing framework is centered around these two
27-- 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 -- , newArray
94 , writeN
95 , write
96 , fromListN
97 , fromList
99 -- Folds
100 , toArrayN
101 -- , toArrays
102 -- , toArray
104 -- Streams
105 , arraysOf
107 -- * Elimination
108 -- 'GHC.Exts.toList' from "GHC.Exts" can be used to convert an array to a
109 -- list.
111 , read
112 , readRev
113 , toList
114 , flattenArrays
115 -- , flattenArraysRev
116 , spliceArrays
118 -- * Random Access
119 , length
120 -- , (!!)
122 , readIndex
123 {-
124 , readSlice
125 , readSliceRev
127 , writeIndex
128 , writeSlice
129 , writeSliceRev
130 -}
131 )
132where
134import Control.Monad.IO.Class (MonadIO(..))
135import Data.Functor.Identity
136import Foreign.ForeignPtr (withForeignPtr)
137import Foreign.Ptr (minusPtr, plusPtr, castPtr)
138import Foreign.Storable (Storable(..))
139import Prelude hiding (length, null, last, map, (!!), read)
141import Streamly.Mem.Array.Types hiding (flattenArrays, newArray)
142import Streamly.Streams.Serial (SerialT)
143import Streamly.Streams.StreamK.Type (IsStream)
144import Streamly.Fold (Fold, lchunksOf, toStream)
146import qualified Streamly.Mem.Array.Types as A
147import qualified Streamly.Prelude as S
148import qualified Streamly.Streams.StreamD as D
150-------------------------------------------------------------------------------
151-- Construction
152-------------------------------------------------------------------------------
154{-
155-- | Create a new uninitialized array of given length.
156--
157-- @since 0.7.0
158newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
159newArray len = undefined
160-}
162-- | Create an 'Array' from the first N elements of a stream. The array is
163-- allocated to size N, if the stream terminates before N elements then the
164-- array may hold less than N elements.
165--
166-- @since 0.7.0
167{-# INLINE writeN #-}
168writeN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
169writeN n m = fromStreamDN n $ D.toStreamD m
171-------------------------------------------------------------------------------
172-- Elimination
173-------------------------------------------------------------------------------
175-- | Convert an 'Array' into a stream in reverse order.
176--
177-- @since 0.7.0
178{-# INLINE_EARLY readRev #-}
179readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
180readRev = D.fromStreamD . toStreamDRev
181-- XXX add fallback to StreamK rule
182-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
183-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
185{-# INLINE _null #-}
186_null :: Storable a => Array a -> Bool
187_null arr = length arr == 0
189{-# INLINE _last #-}
190_last :: forall a. Storable a => Array a -> Maybe a
191_last arr = readIndex arr (length arr - 1)
193-------------------------------------------------------------------------------
194-- Random Access
195-------------------------------------------------------------------------------
197-------------------------------------------------------------------------------
198-- Searching
199-------------------------------------------------------------------------------
201{-
202-- | Perform a binary search in the array to find an element.
203bsearch :: a -> Array a -> Maybe Bool
204bsearch = undefined
206-- | Perform a binary search in the array to find an element index.
207{-# INLINE elemIndex #-}
208bsearchIndex :: a -> Array a -> Maybe Int
209bsearchIndex elem arr = undefined
211-- find/findIndex etc can potentially be implemented more efficiently on arrays
212-- compared to streams by using SIMD instructions.
214find :: (a -> Bool) -> Array a -> Bool
215find = undefined
217findIndex :: (a -> Bool) -> Array a -> Maybe Int
218findIndex = undefined
220findIndices :: (a -> Bool) -> Array a -> Array Int
221findIndices = undefined
222-}
224-------------------------------------------------------------------------------
225-- Folds
226-------------------------------------------------------------------------------
228-- XXX We can potentially use SIMD instructions on arrays to fold faster.
230-------------------------------------------------------------------------------
231-- Slice and splice
232-------------------------------------------------------------------------------
234{-
235slice :: Int -> Int -> Array a
236slice begin end arr = undefined
238splitAt :: Int -> Array a -> (Array a, Array a)
239splitAt i arr = undefined
241-- XXX This operation can be performed efficiently via streams.
242-- | Append two arrays together to create a single array.
243splice :: Array a -> Array a -> Array a
244splice arr1 arr2 = undefined
246-------------------------------------------------------------------------------
247-- In-place mutation APIs
248-------------------------------------------------------------------------------
250-- | Partition an array into two halves using a partitioning predicate. The
251-- first half retains values where the predicate is 'False' and the second half
252-- retains values where the predicate is 'True'.
253{-# INLINE partitionBy #-}
254partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
255partitionBy f arr = undefined
257-- | Shuffle corresponding elements from two arrays using a shuffle function.
258-- If the shuffle function returns 'False' then do nothing otherwise swap the
259-- elements. This can be used in a bottom up fold to shuffle or reorder the
260-- elements.
261shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
262shuffleBy f arr1 arr2 = undefined
264-- XXX we can also make the folds partial by stopping at a certain level.
265--
266-- | Perform a top down hierarchical recursive partitioning fold of items in
267-- the container using the given function as the partition function.
268--
269-- This will perform a quick sort if the partition function is
270-- 'partitionBy (< pivot)'.
271--
272-- @since 0.7.0
273{-# INLINABLE foldtWith #-}
274foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
275foldtWith level f = undefined
277-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
278-- indicates the level in the tree where the fold would stop.
279--
280-- This will perform a random shuffle if the shuffle function is random.
281-- If we stop at level 0 and repeatedly apply the function then we can do a
282-- bubble sort.
283foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
284foldbWith level f = undefined
285-}
287-- XXX consider the bulk update/accumulation/permutation APIs from vector.
289-------------------------------------------------------------------------------
290-- Random reads and writes
291-------------------------------------------------------------------------------
293-- | /O(1)/ Lookup the element at the given index.
294--
295-- @since 0.7.0
296{-# INLINE readIndex #-}
297readIndex :: Storable a => Array a -> Int -> Maybe a
298readIndex arr i =
299 if i < 0 || i > length arr - 1
300 then Nothing
301 else Just $ unsafeIndex arr i
303{-
304-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
305-- at index @i@ and reading up to @count@ elements in the forward direction
306-- ending at the index @i + count - 1@.
307--
308-- @since 0.7.0
309{-# INLINE readSlice #-}
310readSlice :: (IsStream t, Monad m, Storable a)
311 => Array a -> Int -> Int -> t m a
312readSlice arr i len = undefined
314-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
315-- index @i@ and reading up to @count@ elements in the reverse direction ending
316-- at the index @i - count + 1@.
317--
318-- @since 0.7.0
319{-# INLINE readSliceRev #-}
320readSliceRev :: (IsStream t, Monad m, Storable a)
321 => Array a -> Int -> Int -> t m a
322readSliceRev arr i len = undefined
324-- | /O(1)/ Write the given element at the given index in the array.
325--
326-- @since 0.7.0
327{-# INLINE writeIndex #-}
328writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
329writeIndex arr i a = undefined
331-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
332-- starting at index @i@ and writing up to @count@ elements in the forward
333-- direction ending at the index @i + count - 1@.
334--
335-- @since 0.7.0
336{-# INLINE writeSlice #-}
337writeSlice :: (IsStream t, Monad m, Storable a)
338 => Array a -> Int -> Int -> t m a -> m ()
339writeSlice arr i len s = undefined
341-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
342-- starting at index @i@ and writing up to @count@ elements in the reverse
343-- direction ending at the index @i - count + 1@.
344--
345-- @since 0.7.0
346{-# INLINE writeSliceRev #-}
347writeSliceRev :: (IsStream t, Monad m, Storable a)
348 => Array a -> Int -> Int -> t m a -> m ()
349writeSliceRev arr i len s = undefined
350-}
352-------------------------------------------------------------------------------
353-- Streams of Arrays
354-------------------------------------------------------------------------------
356-- | Fold the input to a pure buffered stream (List) of arrays.
357{-# INLINE _toArrays #-}
358_toArrays :: (MonadIO m, Storable a)
359 => Int -> Fold m a (SerialT Identity (Array a))
360_toArrays n = lchunksOf n (toArrayN n) toStream
362-- | Convert a stream of arrays into a stream of their elements.
363--
364-- @since 0.7.0
365{-# INLINE flattenArrays #-}
366flattenArrays :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
367flattenArrays m = D.fromStreamD $ A.flattenArrays (D.toStreamD m)
369-- XXX should we have a reverseArrays API to reverse the stream of arrays
370-- instead?
371--
372-- | Convert a stream of arrays into a stream of their elements reversing the
373-- contents of each array before flattening.
374--
375-- @since 0.7.0
376{-# INLINE _flattenArraysRev #-}
377_flattenArraysRev :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
378_flattenArraysRev m = D.fromStreamD $ A.flattenArraysRev (D.toStreamD m)
380-- |
381-- > arraysOf n = FL.groupsOf n (FL.toArrayN n)
382--
383-- Groups the elements in an input stream into arrays of given size.
384--
385-- @since 0.7.0
386{-# INLINE arraysOf #-}
387arraysOf :: (IsStream t, MonadIO m, Storable a)
388 => Int -> t m a -> t m (Array a)
389arraysOf n str =
390 D.fromStreamD $ fromStreamDArraysOf n (D.toStreamD str)
392-- | Given a stream of arrays, splice them all together to generate a single
393-- array. The stream must be /finite/.
394--
395-- @since 0.7.0
396{-# INLINABLE spliceArrays #-}
397spliceArrays :: (MonadIO m, Storable a) => SerialT m (Array a) -> m (Array a)
398spliceArrays s = do
399 buffered <- S.foldr S.cons S.nil s
400 len <- S.sum (S.map length buffered)
402 arr <- liftIO $ A.newArray len
403 end <- S.foldlM' writeArr (aEnd arr) buffered
404 return $ arr {aEnd = end}
406 where
408 writeArr dst Array{..} =
409 liftIO $ withForeignPtr aStart $ \src -> do
410 let len = aEnd `minusPtr` src
411 memcpy (castPtr dst) (castPtr src) len
412 return $ dst `plusPtr` len
414-- | Create an 'Array' from a stream. This is useful when we want to create a
415-- single array from a stream of unknown size. 'writeN' is at least twice
416-- as efficient when the size is already known.
417--
418-- Note that if the input stream is too large memory allocation for the array
419-- may fail. When the stream size is not known, `arraysOf` followed by
420-- processing of indvidual arrays in the resulting stream should be preferred.
421--
422{-# INLINE write #-}
423write :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
424write m = A.fromStreamD $ D.toStreamD m
426-- XXX efficiently compare two streams of arrays. Two streams can have chunks
427-- of different sizes, we can handle that in the stream comparison abstraction.
428-- This could be useful e.g. to fast compare whether two files differ.