on cb4a2bb help sign in
576 lines 19 kB history raw
1{-# LANGUAGE UnboxedTuples #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Internal.Data.Array.Foreign
7-- Copyright : (c) 2019 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
14-- To summarize:
15--
16-- * Arrays are finite and fixed in size
17-- * provide /O(1)/ access to elements
18-- * store only data and not functions
19-- * provide efficient IO interfacing
20--
21-- 'Foldable' instance is not provided because the implementation would be much
22-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
23-- instances should be used with care; concatenating arrays using binary
24-- operations can be highly inefficient. Instead, use
25-- 'Streamly.Internal.Data.Array.Stream.Foreign.toArray' to concatenate N
26-- arrays at once.
27--
28-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
29-- single byte) are only as good as holding those elements in a Haskell list.
30-- However, small arrays can be compacted into large ones to reduce the
31-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
32-- if we use one array for each chunk. This is still significant to add
33-- pressure to GC.
35module Streamly.Internal.Data.Array.Foreign
36 (
37 Array
39 -- , defaultChunkSize
41 -- * Construction
43 -- Pure, From Static Memory (Unsafe)
44 -- We can use fromPtrM#, fromCStringM# and fromAddrM# to create arrays from
45 -- a dynamic memory address which requires a finalizer.
46 , A.fromPtr
47 , A.fromAddr#
48 , A.fromCString#
50 -- Pure List APIs
51 , A.fromListN
52 , A.fromList
54 -- Stream Folds
55 , fromStreamN
56 , fromStream
58 -- Monadic APIs
59 -- , newArray
60 , A.writeN -- drop new
61 , A.writeNAligned
62 , A.write -- full buffer
63 -- , writeLastN -- drop old (ring buffer)
65 -- * Elimination
67 , A.toList
68 , A.toStream
69 , A.toStreamRev
70 , read
71 , producer
72 , unsafeRead
73 , A.readRev
74 -- , readChunksOf
76 -- * Random Access
77 , length
78 , null
79 , last
80 -- , (!!)
81 , readIndex
82 , A.unsafeIndex
83 -- , readIndices
84 -- , readRanges
86 -- , readFrom -- read from a given position to the end of file
87 -- , readFromRev -- read from a given position to the beginning of file
88 -- , readTo -- read from beginning up to the given position
89 -- , readToRev -- read from end to the given position in file
90 -- , readFromTo
91 -- , readFromThenTo
93 -- , readChunksOfFrom
94 -- , ...
96 -- , writeIndex
97 -- , writeFrom -- start writing at the given position
98 -- , writeFromRev
99 -- , writeTo -- write from beginning up to the given position
100 -- , writeToRev
101 -- , writeFromTo
102 -- , writeFromThenTo
103 --
104 -- , writeChunksOfFrom
105 -- , ...
107 , writeIndex
108 --, writeIndices
109 --, writeRanges
111 -- -- * Search
112 -- , bsearch
113 -- , bsearchIndex
114 -- , find
115 -- , findIndex
116 -- , findIndices
118 -- -- * In-pace mutation (for Mutable Array type)
119 -- , partitionBy
120 -- , shuffleBy
121 -- , foldtWith
122 -- , foldbWith
124 -- * Immutable Transformations
125 , streamTransform
127 -- * Casting
128 , cast
129 , unsafeCast
130 , asPtr
131 , asByteArray
132 , asCString
134 -- * Folding Arrays
135 , streamFold
136 , fold
138 -- * Folds with Array as the container
139 , lastN
140 )
141where
143import Control.Monad (when)
144import Control.Monad.IO.Class (MonadIO(..))
145#if !(MIN_VERSION_base(4,11,0))
146import Data.Semigroup ((<>))
147#endif
148import Data.Word (Word8)
149-- import Data.Functor.Identity (Identity)
150import Foreign.C.String (CString)
151import Foreign.ForeignPtr (withForeignPtr, castForeignPtr)
152import Foreign.Ptr (plusPtr, castPtr)
153import Foreign.Storable (Storable(..))
154import Prelude hiding (length, null, last, map, (!!), read, concat)
156import GHC.ForeignPtr (ForeignPtr(..))
157import GHC.Ptr (Ptr(..))
158import GHC.Prim (touch#)
159import GHC.IO (IO(..))
161import Streamly.Internal.Data.Array.Foreign.Types (Array(..), length)
162import Streamly.Internal.Data.Fold.Types (Fold(..))
163import Streamly.Internal.Data.Producer.Type (Producer)
164import Streamly.Internal.Data.Stream.Serial (SerialT)
165import Streamly.Internal.Data.Tuple.Strict (Tuple3'(..))
166import Streamly.Internal.Data.Unfold.Types (Unfold(..))
168import qualified Streamly.Internal.Data.Array.Foreign.Mut.Types as MA
169import qualified Streamly.Internal.Data.Array.Foreign.Types as A
170import qualified Streamly.Internal.Data.Fold as FL
171import qualified Streamly.Internal.Data.Stream.Prelude as P
172import qualified Streamly.Internal.Data.Stream.Serial as Serial
173import qualified Streamly.Internal.Data.Stream.StreamD as D
174import qualified Streamly.Internal.Data.Unfold as Unfold
175import qualified Streamly.Internal.Data.Producer.Type as Producer
176import qualified Streamly.Internal.Ring.Foreign as RB
178-------------------------------------------------------------------------------
179-- Construction
180-------------------------------------------------------------------------------
182-- | Create an 'Array' from the first N elements of a stream. The array is
183-- allocated to size N, if the stream terminates before N elements then the
184-- array may hold less than N elements.
185--
186-- /Pre-release/
187{-# INLINE fromStreamN #-}
188fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
189fromStreamN n m = do
190 when (n < 0) $ error "writeN: negative write count specified"
191 A.fromStreamDN n $ D.toStreamD m
193-- | Create an 'Array' from a stream. This is useful when we want to create a
194-- single array from a stream of unknown size. 'writeN' is at least twice
195-- as efficient when the size is already known.
196--
197-- Note that if the input stream is too large memory allocation for the array
198-- may fail. When the stream size is not known, `arraysOf` followed by
199-- processing of indvidual arrays in the resulting stream should be preferred.
200--
201-- /Pre-release/
202{-# INLINE fromStream #-}
203fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
204fromStream = P.foldOnce A.write
205-- write m = A.fromStreamD $ D.toStreamD m
207-------------------------------------------------------------------------------
208-- Elimination
209-------------------------------------------------------------------------------
211-- | Unfold an array into a stream.
212--
213-- @since 0.7.0
214{-# INLINE_NORMAL read #-}
215read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
216read = Unfold.lmap A.unsafeThaw MA.read
218{-# INLINE_NORMAL producer #-}
219producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
220producer = Producer.translate A.unsafeThaw A.unsafeFreeze MA.producer
222-- | Unfold an array into a stream, does not check the end of the array, the
223-- user is responsible for terminating the stream within the array bounds. For
224-- high performance application where the end condition can be determined by
225-- a terminating fold.
226--
227-- Written in the hope that it may be faster than "read", however, in the case
228-- for which this was written, "read" proves to be faster even though the core
229-- generated with unsafeRead looks simpler.
230--
231-- /Pre-release/
232--
233{-# INLINE_NORMAL unsafeRead #-}
234unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
235unsafeRead = Unfold step inject
236 where
238 inject (Array fp _) = return fp
240 {-# INLINE_LATE step #-}
241 step (ForeignPtr p contents) = do
242 -- unsafeInlineIO allows us to run this in Identity monad for pure
243 -- toList/foldr case which makes them much faster due to not
244 -- accumulating the list and fusing better with the pure consumers.
245 --
246 -- This should be safe as the array contents are guaranteed to be
247 -- evaluated/written to before we peek at them.
248 let !x = A.unsafeInlineIO $ do
249 r <- peek (Ptr p)
250 touch contents
251 return r
252 let !(Ptr p1) = Ptr p `plusPtr` sizeOf (undefined :: a)
253 return $ D.Yield x (ForeignPtr p1 contents)
255 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
257-- | > null arr = length arr == 0
258--
259-- /Pre-release/
260{-# INLINE null #-}
261null :: Storable a => Array a -> Bool
262null arr = length arr == 0
264-- | > last arr = readIndex arr (length arr - 1)
265--
266-- /Pre-release/
267{-# INLINE last #-}
268last :: Storable a => Array a -> Maybe a
269last arr = readIndex arr (length arr - 1)
271-------------------------------------------------------------------------------
272-- Folds with Array as the container
273-------------------------------------------------------------------------------
275-- | Take last 'n' elements from the stream and discard the rest.
276{-# INLINE lastN #-}
277lastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
278lastN n
279 | n <= 0 = fmap (const mempty) FL.drain
280 | otherwise = A.unsafeFreeze <$> Fold step initial done
281 where
282 step (Tuple3' rb rh i) a = do
283 rh1 <- liftIO $ RB.unsafeInsert rb rh a
284 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
285 initial =
286 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
287 in fmap f $ liftIO $ RB.new n
288 done (Tuple3' rb rh i) = do
289 arr <- liftIO $ MA.newArray n
290 foldFunc i rh snoc' arr rb
291 snoc' b a = liftIO $ MA.unsafeSnoc b a
292 foldFunc i
293 | i < n = RB.unsafeFoldRingM
294 | otherwise = RB.unsafeFoldRingFullM
296-------------------------------------------------------------------------------
297-- Random Access
298-------------------------------------------------------------------------------
300-------------------------------------------------------------------------------
301-- Searching
302-------------------------------------------------------------------------------
304{-
305-- | Perform a binary search in the array to find an element.
306bsearch :: a -> Array a -> Maybe Bool
307bsearch = undefined
309-- | Perform a binary search in the array to find an element index.
310{-# INLINE elemIndex #-}
311bsearchIndex :: a -> Array a -> Maybe Int
312bsearchIndex elem arr = undefined
314-- find/findIndex etc can potentially be implemented more efficiently on arrays
315-- compared to streams by using SIMD instructions.
317find :: (a -> Bool) -> Array a -> Bool
318find = undefined
320findIndex :: (a -> Bool) -> Array a -> Maybe Int
321findIndex = undefined
323findIndices :: (a -> Bool) -> Array a -> Array Int
324findIndices = undefined
325-}
327-------------------------------------------------------------------------------
328-- Folds
329-------------------------------------------------------------------------------
331-- XXX We can potentially use SIMD instructions on arrays to fold faster.
333-------------------------------------------------------------------------------
334-- Slice and splice
335-------------------------------------------------------------------------------
337{-
338slice :: Int -> Int -> Array a
339slice begin end arr = undefined
341splitAt :: Int -> Array a -> (Array a, Array a)
342splitAt i arr = undefined
344-- XXX This operation can be performed efficiently via streams.
345-- | Append two arrays together to create a single array.
346splice :: Array a -> Array a -> Array a
347splice arr1 arr2 = undefined
349-------------------------------------------------------------------------------
350-- In-place mutation APIs
351-------------------------------------------------------------------------------
353-- | Partition an array into two halves using a partitioning predicate. The
354-- first half retains values where the predicate is 'False' and the second half
355-- retains values where the predicate is 'True'.
356{-# INLINE partitionBy #-}
357partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
358partitionBy f arr = undefined
360-- | Shuffle corresponding elements from two arrays using a shuffle function.
361-- If the shuffle function returns 'False' then do nothing otherwise swap the
362-- elements. This can be used in a bottom up fold to shuffle or reorder the
363-- elements.
364shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
365shuffleBy f arr1 arr2 = undefined
367-- XXX we can also make the folds partial by stopping at a certain level.
368--
369-- | Perform a top down hierarchical recursive partitioning fold of items in
370-- the container using the given function as the partition function.
371--
372-- This will perform a quick sort if the partition function is
373-- 'partitionBy (< pivot)'.
374--
375-- @since 0.7.0
376{-# INLINABLE foldtWith #-}
377foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
378foldtWith level f = undefined
380-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
381-- indicates the level in the tree where the fold would stop.
382--
383-- This will perform a random shuffle if the shuffle function is random.
384-- If we stop at level 0 and repeatedly apply the function then we can do a
385-- bubble sort.
386foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
387foldbWith level f = undefined
388-}
390-- XXX consider the bulk update/accumulation/permutation APIs from vector.
392-------------------------------------------------------------------------------
393-- Random reads and writes
394-------------------------------------------------------------------------------
396-- | /O(1)/ Lookup the element at the given index, starting from 0.
397--
398-- /Pre-release/
399{-# INLINE readIndex #-}
400readIndex :: Storable a => Array a -> Int -> Maybe a
401readIndex arr i =
402 if i < 0 || i > length arr - 1
403 then Nothing
404 else A.unsafeInlineIO $
405 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
407{-
408-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
409-- at index @i@ and reading up to @count@ elements in the forward direction
410-- ending at the index @i + count - 1@.
411--
412-- @since 0.7.0
413{-# INLINE readSlice #-}
414readSlice :: (IsStream t, Monad m, Storable a)
415 => Array a -> Int -> Int -> t m a
416readSlice arr i len = undefined
418-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
419-- index @i@ and reading up to @count@ elements in the reverse direction ending
420-- at the index @i - count + 1@.
421--
422-- @since 0.7.0
423{-# INLINE readSliceRev #-}
424readSliceRev :: (IsStream t, Monad m, Storable a)
425 => Array a -> Int -> Int -> t m a
426readSliceRev arr i len = undefined
427-}
429-- | /O(1)/ Write the given element at the given index in the array.
430-- Performs in-place mutation of the array.
431--
432-- /Pre-release/
433{-# INLINE writeIndex #-}
434writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
435writeIndex arr i a = do
436 let maxIndex = length arr - 1
437 if i < 0
438 then error "writeIndex: negative array index"
439 else if i > maxIndex
440 then error $ "writeIndex: specified array index " ++ show i
441 ++ " is beyond the maximum index " ++ show maxIndex
442 else
443 liftIO $ withForeignPtr (aStart arr) $ \p ->
444 pokeElemOff p i a
446{-
447-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
448-- starting at index @i@ and writing up to @count@ elements in the forward
449-- direction ending at the index @i + count - 1@.
450--
451-- @since 0.7.0
452{-# INLINE writeSlice #-}
453writeSlice :: (IsStream t, Monad m, Storable a)
454 => Array a -> Int -> Int -> t m a -> m (Array a)
455writeSlice arr i len s = undefined
457-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
458-- starting at index @i@ and writing up to @count@ elements in the reverse
459-- direction ending at the index @i - count + 1@.
460--
461-- @since 0.7.0
462{-# INLINE writeSliceRev #-}
463writeSliceRev :: (IsStream t, Monad m, Storable a)
464 => Array a -> Int -> Int -> t m a -> m (Array a)
465writeSliceRev arr i len s = undefined
466-}
468-------------------------------------------------------------------------------
469-- Transform via stream operations
470-------------------------------------------------------------------------------
472-- for non-length changing operations we can use the original length for
473-- allocation. If we can predict the length then we can use the prediction for
474-- new allocation. Otherwise we can use a hint and adjust dynamically.
476{-
477-- | Transform an array into another array using a pipe transformation
478-- operation.
479--
480-- @since 0.7.0
481{-# INLINE runPipe #-}
482runPipe :: (MonadIO m, Storable a, Storable b)
483 => Pipe m a b -> Array a -> m (Array b)
484runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
485-}
487-- | Transform an array into another array using a stream transformation
488-- operation.
489--
490-- /Pre-release/
491{-# INLINE streamTransform #-}
492streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
493 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
494streamTransform f arr =
495 P.foldOnce (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
496 $ f (A.toStream arr)
498-------------------------------------------------------------------------------
499-- Casts
500-------------------------------------------------------------------------------
502-- | Cast an array having elements of type @a@ into an array having elements of
503-- type @b@. The array size must be a multiple of the size of type @b@
504-- otherwise accessing the last element of the array may result into a crash or
505-- a random value.
506--
507-- /Pre-release/
508--
509unsafeCast ::
510#ifdef DEVBUILD
511 Storable b =>
512#endif
513 Array a -> Array b
514unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
516-- | Cast an array into a Word8 array
517--
518-- /Pre-release/
519--
520asByteArray :: Array a -> Array Word8
521asByteArray = unsafeCast
523-- | Cast an array having elements of type @a@ into an array having elements of
524-- type @b@. The length of the array should be a multiple of the size of the
525-- target element otherwise 'Nothing' is returned.
526--
527-- /Pre-release/
528--
529cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
530cast arr =
531 let len = A.byteLength arr
532 r = len `mod` sizeOf (undefined :: b)
533 in if r /= 0
534 then Nothing
535 else Just $ unsafeCast arr
537-- | Use an @Array a@ as @Ptr b@.
538--
539-- /Unsafe/
540--
541-- /Pre-release/
542--
543asPtr :: Array a -> (Ptr b -> IO c) -> IO c
544asPtr Array{..} act = do
545 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
547-- | Convert an array of any type into a null terminated CString Ptr.
548--
549-- /Unsafe/
550--
551-- /O(n) Time: (creates a copy of the array)/
552--
553-- /Pre-release/
554--
555asCString :: Array a -> (CString -> IO b) -> IO b
556asCString arr act = do
557 let Array{..} = asByteArray arr <> A.fromList [0]
558 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
560-------------------------------------------------------------------------------
561-- Folds
562-------------------------------------------------------------------------------
564-- | Fold an array using a 'Fold'.
565--
566-- /Pre-release/
567{-# INLINE fold #-}
568fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
569fold f arr = P.foldOnce f (A.toStream arr :: Serial.SerialT m a)
571-- | Fold an array using a stream fold operation.
572--
573-- /Pre-release/
574{-# INLINE streamFold #-}
575streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
576streamFold f arr = f (A.toStream arr)