on fc6d77a help sign in
430 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 Foreign.ForeignPtr (withForeignPtr)
136import Foreign.Ptr (minusPtr, plusPtr, castPtr)
137import Foreign.Storable (Storable(..))
138import Prelude hiding (length, null, last, map, (!!), read)
140import Streamly.Mem.Array.Types hiding (flattenArrays, newArray)
141import Streamly.Streams.Serial (SerialT)
142import Streamly.Streams.StreamK.Type (IsStream)
144import qualified Streamly.Mem.Array.Types as A
145import qualified Streamly.Prelude as S
146import qualified Streamly.Streams.StreamD as D
148-------------------------------------------------------------------------------
149-- Construction
150-------------------------------------------------------------------------------
152{-
153-- | Create a new uninitialized array of given length.
154--
155-- @since 0.7.0
156newArray :: (MonadIO m, Storable a) => Int -> m (Array a)
157newArray len = undefined
158-}
160-- | Create an 'Array' from the first N elements of a stream. The array is
161-- allocated to size N, if the stream terminates before N elements then the
162-- array may hold less than N elements.
163--
164-- @since 0.7.0
165{-# INLINE writeN #-}
166writeN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
167writeN n m = fromStreamDN n $ D.toStreamD m
169-------------------------------------------------------------------------------
170-- Elimination
171-------------------------------------------------------------------------------
173-- | Convert an 'Array' into a stream.
174--
175-- @since 0.7.0
176{-# INLINE_EARLY read #-}
177read :: (Monad m, IsStream t, Storable a) => Array a -> t m a
178read = D.fromStreamD . toStreamD
179-- XXX add fallback to StreamK rule
180-- {-# RULES "Streamly.Array.read fallback to StreamK" [1]
181-- forall a. S.readK (read a) = K.fromArray a #-}
183-- | Convert an 'Array' into a stream in reverse order.
184--
185-- @since 0.7.0
186{-# INLINE_EARLY readRev #-}
187readRev :: (Monad m, IsStream t, Storable a) => Array a -> t m a
188readRev = D.fromStreamD . toStreamDRev
189-- XXX add fallback to StreamK rule
190-- {-# RULES "Streamly.Array.readRev fallback to StreamK" [1]
191-- forall a. S.toStreamK (readRev a) = K.revFromArray a #-}
193{-# INLINE _null #-}
194_null :: Storable a => Array a -> Bool
195_null arr = length arr == 0
197{-# INLINE _last #-}
198_last :: forall a. Storable a => Array a -> Maybe a
199_last arr = readIndex arr (length arr - 1)
201-------------------------------------------------------------------------------
202-- Random Access
203-------------------------------------------------------------------------------
205-------------------------------------------------------------------------------
206-- Searching
207-------------------------------------------------------------------------------
209{-
210-- | Perform a binary search in the array to find an element.
211bsearch :: a -> Array a -> Maybe Bool
212bsearch = undefined
214-- | Perform a binary search in the array to find an element index.
215{-# INLINE elemIndex #-}
216bsearchIndex :: a -> Array a -> Maybe Int
217bsearchIndex elem arr = undefined
219-- find/findIndex etc can potentially be implemented more efficiently on arrays
220-- compared to streams by using SIMD instructions.
222find :: (a -> Bool) -> Array a -> Bool
223find = undefined
225findIndex :: (a -> Bool) -> Array a -> Maybe Int
226findIndex = undefined
228findIndices :: (a -> Bool) -> Array a -> Array Int
229findIndices = undefined
230-}
232-------------------------------------------------------------------------------
233-- Folds
234-------------------------------------------------------------------------------
236-- XXX We can potentially use SIMD instructions on arrays to fold faster.
238-------------------------------------------------------------------------------
239-- Slice and splice
240-------------------------------------------------------------------------------
242{-
243slice :: Int -> Int -> Array a
244slice begin end arr = undefined
246splitAt :: Int -> Array a -> (Array a, Array a)
247splitAt i arr = undefined
249-- XXX This operation can be performed efficiently via streams.
250-- | Append two arrays together to create a single array.
251splice :: Array a -> Array a -> Array a
252splice arr1 arr2 = undefined
254-------------------------------------------------------------------------------
255-- In-place mutation APIs
256-------------------------------------------------------------------------------
258-- | Partition an array into two halves using a partitioning predicate. The
259-- first half retains values where the predicate is 'False' and the second half
260-- retains values where the predicate is 'True'.
261{-# INLINE partitionBy #-}
262partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
263partitionBy f arr = undefined
265-- | Shuffle corresponding elements from two arrays using a shuffle function.
266-- If the shuffle function returns 'False' then do nothing otherwise swap the
267-- elements. This can be used in a bottom up fold to shuffle or reorder the
268-- elements.
269shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
270shuffleBy f arr1 arr2 = undefined
272-- XXX we can also make the folds partial by stopping at a certain level.
273--
274-- | Perform a top down hierarchical recursive partitioning fold of items in
275-- the container using the given function as the partition function.
276--
277-- This will perform a quick sort if the partition function is
278-- 'partitionBy (< pivot)'.
279--
280-- @since 0.7.0
281{-# INLINABLE foldtWith #-}
282foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
283foldtWith level f = undefined
285-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
286-- indicates the level in the tree where the fold would stop.
287--
288-- This will perform a random shuffle if the shuffle function is random.
289-- If we stop at level 0 and repeatedly apply the function then we can do a
290-- bubble sort.
291foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
292foldbWith level f = undefined
293-}
295-- XXX consider the bulk update/accumulation/permutation APIs from vector.
297-------------------------------------------------------------------------------
298-- Random reads and writes
299-------------------------------------------------------------------------------
301-- | /O(1)/ Lookup the element at the given index.
302--
303-- @since 0.7.0
304{-# INLINE readIndex #-}
305readIndex :: Storable a => Array a -> Int -> Maybe a
306readIndex arr i =
307 if i < 0 || i > length arr - 1
308 then Nothing
309 else Just $ unsafeIndex arr i
311{-
312-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
313-- at index @i@ and reading up to @count@ elements in the forward direction
314-- ending at the index @i + count - 1@.
315--
316-- @since 0.7.0
317{-# INLINE readSlice #-}
318readSlice :: (IsStream t, Monad m, Storable a)
319 => Array a -> Int -> Int -> t m a
320readSlice arr i len = undefined
322-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
323-- index @i@ and reading up to @count@ elements in the reverse direction ending
324-- at the index @i - count + 1@.
325--
326-- @since 0.7.0
327{-# INLINE readSliceRev #-}
328readSliceRev :: (IsStream t, Monad m, Storable a)
329 => Array a -> Int -> Int -> t m a
330readSliceRev arr i len = undefined
332-- | /O(1)/ Write the given element at the given index in the array.
333--
334-- @since 0.7.0
335{-# INLINE writeIndex #-}
336writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
337writeIndex arr i a = undefined
339-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
340-- starting at index @i@ and writing up to @count@ elements in the forward
341-- direction ending at the index @i + count - 1@.
342--
343-- @since 0.7.0
344{-# INLINE writeSlice #-}
345writeSlice :: (IsStream t, Monad m, Storable a)
346 => Array a -> Int -> Int -> t m a -> m ()
347writeSlice arr i len s = undefined
349-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
350-- starting at index @i@ and writing up to @count@ elements in the reverse
351-- direction ending at the index @i - count + 1@.
352--
353-- @since 0.7.0
354{-# INLINE writeSliceRev #-}
355writeSliceRev :: (IsStream t, Monad m, Storable a)
356 => Array a -> Int -> Int -> t m a -> m ()
357writeSliceRev arr i len s = undefined
358-}
360-------------------------------------------------------------------------------
361-- Streams of Arrays
362-------------------------------------------------------------------------------
364-- | Convert a stream of arrays into a stream of their elements.
365--
366-- @since 0.7.0
367{-# INLINE flattenArrays #-}
368flattenArrays :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
369flattenArrays m = D.fromStreamD $ A.flattenArrays (D.toStreamD m)
371-- XXX should we have a reverseArrays API to reverse the stream of arrays
372-- instead?
373--
374-- | Convert a stream of arrays into a stream of their elements reversing the
375-- contents of each array before flattening.
376--
377-- @since 0.7.0
378{-# INLINE _flattenArraysRev #-}
379_flattenArraysRev :: (IsStream t, MonadIO m, Storable a) => t m (Array a) -> t m a
380_flattenArraysRev m = D.fromStreamD $ A.flattenArraysRev (D.toStreamD m)
382-- |
383-- > arraysOf n = FL.groupsOf n (FL.toArrayN n)
384--
385-- Groups the elements in an input stream into arrays of given size.
386--
387-- @since 0.7.0
388{-# INLINE arraysOf #-}
389arraysOf :: (IsStream t, MonadIO m, Storable a)
390 => Int -> t m a -> t m (Array a)
391arraysOf n str =
392 D.fromStreamD $ fromStreamDArraysOf n (D.toStreamD str)
394-- | Given a stream of arrays, splice them all together to generate a single
395-- array. The stream must be /finite/.
396--
397-- @since 0.7.0
398{-# INLINABLE spliceArrays #-}
399spliceArrays :: (MonadIO m, Storable a) => SerialT m (Array a) -> m (Array a)
400spliceArrays s = do
401 buffered <- S.foldr S.cons S.nil s
402 len <- S.sum (S.map length buffered)
404 arr <- liftIO $ A.newArray len
405 end <- S.foldlM' writeArr (aEnd arr) buffered
406 return $ arr {aEnd = end}
408 where
410 writeArr dst Array{..} =
411 liftIO $ withForeignPtr aStart $ \src -> do
412 let len = aEnd `minusPtr` src
413 memcpy (castPtr dst) (castPtr src) len
414 return $ dst `plusPtr` len
416-- | Create an 'Array' from a stream. This is useful when we want to create a
417-- single array from a stream of unknown size. 'writeN' is at least twice
418-- as efficient when the size is already known.
419--
420-- Note that if the input stream is too large memory allocation for the array
421-- may fail. When the stream size is not known, `arraysOf` followed by
422-- processing of indvidual arrays in the resulting stream should be preferred.
423--
424{-# INLINE write #-}
425write :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
426write m = A.fromStreamD $ D.toStreamD m
428-- XXX efficiently compare two streams of arrays. Two streams can have chunks
429-- of different sizes, we can handle that in the stream comparison abstraction.
430-- This could be useful e.g. to fast compare whether two files differ.