on bffdd45 help sign in
568 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 , unsafeRead
72 -- , readChunksOf
74 -- * Random Access
75 , length
76 , null
77 , last
78 -- , (!!)
79 , readIndex
80 , A.unsafeIndex
81 -- , readIndices
82 -- , readRanges
84 -- , readFrom -- read from a given position to the end of file
85 -- , readFromRev -- read from a given position to the beginning of file
86 -- , readTo -- read from beginning up to the given position
87 -- , readToRev -- read from end to the given position in file
88 -- , readFromTo
89 -- , readFromThenTo
91 -- , readChunksOfFrom
92 -- , ...
94 -- , writeIndex
95 -- , writeFrom -- start writing at the given position
96 -- , writeFromRev
97 -- , writeTo -- write from beginning up to the given position
98 -- , writeToRev
99 -- , writeFromTo
100 -- , writeFromThenTo
101 --
102 -- , writeChunksOfFrom
103 -- , ...
105 , writeIndex
106 --, writeIndices
107 --, writeRanges
109 -- -- * Search
110 -- , bsearch
111 -- , bsearchIndex
112 -- , find
113 -- , findIndex
114 -- , findIndices
116 -- -- * In-pace mutation (for Mutable Array type)
117 -- , partitionBy
118 -- , shuffleBy
119 -- , foldtWith
120 -- , foldbWith
122 -- * Immutable Transformations
123 , streamTransform
125 -- * Casting
126 , cast
127 , unsafeCast
128 , asPtr
129 , asByteArray
130 , asCString
132 -- * Folding Arrays
133 , streamFold
134 , fold
136 -- * Folds with Array as the container
137 , lastN
138 )
139where
141import Control.Monad (when)
142import Control.Monad.IO.Class (MonadIO(..))
143#if !(MIN_VERSION_base(4,11,0))
144import Data.Semigroup ((<>))
145#endif
146import Data.Word (Word8)
147-- import Data.Functor.Identity (Identity)
148import Foreign.C.String (CString)
149import Foreign.ForeignPtr (withForeignPtr, castForeignPtr)
150import Foreign.Ptr (plusPtr, castPtr)
151import Foreign.Storable (Storable(..))
152import Prelude hiding (length, null, last, map, (!!), read, concat)
154import GHC.ForeignPtr (ForeignPtr(..))
155import GHC.Ptr (Ptr(..))
156import GHC.Prim (touch#)
157import GHC.IO (IO(..))
159import Streamly.Internal.Data.Array.Foreign.Types (Array(..), length)
160import Streamly.Internal.Data.Fold.Types (Fold(..))
161import Streamly.Internal.Data.Stream.Serial (SerialT)
162import Streamly.Internal.Data.Tuple.Strict (Tuple3'(..))
163import Streamly.Internal.Data.Unfold.Types (Unfold(..))
165import qualified Streamly.Internal.Data.Array.Foreign.Mut.Types as MA
166import qualified Streamly.Internal.Data.Array.Foreign.Types as A
167import qualified Streamly.Internal.Data.Fold as FL
168import qualified Streamly.Internal.Data.Stream.Prelude as P
169import qualified Streamly.Internal.Data.Stream.Serial as Serial
170import qualified Streamly.Internal.Data.Stream.StreamD as D
171import qualified Streamly.Internal.Data.Unfold as Unfold
172import qualified Streamly.Internal.Ring.Foreign as RB
174-------------------------------------------------------------------------------
175-- Construction
176-------------------------------------------------------------------------------
178-- | Create an 'Array' from the first N elements of a stream. The array is
179-- allocated to size N, if the stream terminates before N elements then the
180-- array may hold less than N elements.
181--
182-- /Internal/
183{-# INLINE fromStreamN #-}
184fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
185fromStreamN n m = do
186 when (n < 0) $ error "writeN: negative write count specified"
187 A.fromStreamDN n $ D.toStreamD m
189-- | Create an 'Array' from a stream. This is useful when we want to create a
190-- single array from a stream of unknown size. 'writeN' is at least twice
191-- as efficient when the size is already known.
192--
193-- Note that if the input stream is too large memory allocation for the array
194-- may fail. When the stream size is not known, `arraysOf` followed by
195-- processing of indvidual arrays in the resulting stream should be preferred.
196--
197-- /Internal/
198{-# INLINE fromStream #-}
199fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
200fromStream = P.foldOnce A.write
201-- write m = A.fromStreamD $ D.toStreamD m
203-------------------------------------------------------------------------------
204-- Elimination
205-------------------------------------------------------------------------------
207-- | Unfold an array into a stream.
208--
209-- @since 0.7.0
210{-# INLINE_NORMAL read #-}
211read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
212read = Unfold.lmap A.unsafeThaw MA.read
214-- | Unfold an array into a stream, does not check the end of the array, the
215-- user is responsible for terminating the stream within the array bounds. For
216-- high performance application where the end condition can be determined by
217-- a terminating fold.
218--
219-- Written in the hope that it may be faster than "read", however, in the case
220-- for which this was written, "read" proves to be faster even though the core
221-- generated with unsafeRead looks simpler.
222--
223-- /Internal/
224--
225{-# INLINE_NORMAL unsafeRead #-}
226unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
227unsafeRead = Unfold step inject
228 where
230 inject (Array fp _) = return fp
232 {-# INLINE_LATE step #-}
233 step (ForeignPtr p contents) = do
234 -- unsafeInlineIO allows us to run this in Identity monad for pure
235 -- toList/foldr case which makes them much faster due to not
236 -- accumulating the list and fusing better with the pure consumers.
237 --
238 -- This should be safe as the array contents are guaranteed to be
239 -- evaluated/written to before we peek at them.
240 let !x = A.unsafeInlineIO $ do
241 r <- peek (Ptr p)
242 touch contents
243 return r
244 let !(Ptr p1) = Ptr p `plusPtr` sizeOf (undefined :: a)
245 return $ D.Yield x (ForeignPtr p1 contents)
247 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
249-- | > null arr = length arr == 0
250--
251-- /Internal/
252{-# INLINE null #-}
253null :: Storable a => Array a -> Bool
254null arr = length arr == 0
256-- | > last arr = readIndex arr (length arr - 1)
257--
258-- /Internal/
259{-# INLINE last #-}
260last :: Storable a => Array a -> Maybe a
261last arr = readIndex arr (length arr - 1)
263-------------------------------------------------------------------------------
264-- Folds with Array as the container
265-------------------------------------------------------------------------------
267-- | Take last 'n' elements from the stream and discard the rest.
268{-# INLINE lastN #-}
269lastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
270lastN n
271 | n <= 0 = fmap (const mempty) FL.drain
272 | otherwise = A.unsafeFreeze <$> Fold step initial done
273 where
274 step (Tuple3' rb rh i) a = do
275 rh1 <- liftIO $ RB.unsafeInsert rb rh a
276 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
277 initial =
278 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
279 in fmap f $ liftIO $ RB.new n
280 done (Tuple3' rb rh i) = do
281 arr <- liftIO $ MA.newArray n
282 foldFunc i rh snoc' arr rb
283 snoc' b a = liftIO $ MA.unsafeSnoc b a
284 foldFunc i
285 | i < n = RB.unsafeFoldRingM
286 | otherwise = RB.unsafeFoldRingFullM
288-------------------------------------------------------------------------------
289-- Random Access
290-------------------------------------------------------------------------------
292-------------------------------------------------------------------------------
293-- Searching
294-------------------------------------------------------------------------------
296{-
297-- | Perform a binary search in the array to find an element.
298bsearch :: a -> Array a -> Maybe Bool
299bsearch = undefined
301-- | Perform a binary search in the array to find an element index.
302{-# INLINE elemIndex #-}
303bsearchIndex :: a -> Array a -> Maybe Int
304bsearchIndex elem arr = undefined
306-- find/findIndex etc can potentially be implemented more efficiently on arrays
307-- compared to streams by using SIMD instructions.
309find :: (a -> Bool) -> Array a -> Bool
310find = undefined
312findIndex :: (a -> Bool) -> Array a -> Maybe Int
313findIndex = undefined
315findIndices :: (a -> Bool) -> Array a -> Array Int
316findIndices = undefined
317-}
319-------------------------------------------------------------------------------
320-- Folds
321-------------------------------------------------------------------------------
323-- XXX We can potentially use SIMD instructions on arrays to fold faster.
325-------------------------------------------------------------------------------
326-- Slice and splice
327-------------------------------------------------------------------------------
329{-
330slice :: Int -> Int -> Array a
331slice begin end arr = undefined
333splitAt :: Int -> Array a -> (Array a, Array a)
334splitAt i arr = undefined
336-- XXX This operation can be performed efficiently via streams.
337-- | Append two arrays together to create a single array.
338splice :: Array a -> Array a -> Array a
339splice arr1 arr2 = undefined
341-------------------------------------------------------------------------------
342-- In-place mutation APIs
343-------------------------------------------------------------------------------
345-- | Partition an array into two halves using a partitioning predicate. The
346-- first half retains values where the predicate is 'False' and the second half
347-- retains values where the predicate is 'True'.
348{-# INLINE partitionBy #-}
349partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
350partitionBy f arr = undefined
352-- | Shuffle corresponding elements from two arrays using a shuffle function.
353-- If the shuffle function returns 'False' then do nothing otherwise swap the
354-- elements. This can be used in a bottom up fold to shuffle or reorder the
355-- elements.
356shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
357shuffleBy f arr1 arr2 = undefined
359-- XXX we can also make the folds partial by stopping at a certain level.
360--
361-- | Perform a top down hierarchical recursive partitioning fold of items in
362-- the container using the given function as the partition function.
363--
364-- This will perform a quick sort if the partition function is
365-- 'partitionBy (< pivot)'.
366--
367-- @since 0.7.0
368{-# INLINABLE foldtWith #-}
369foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
370foldtWith level f = undefined
372-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
373-- indicates the level in the tree where the fold would stop.
374--
375-- This will perform a random shuffle if the shuffle function is random.
376-- If we stop at level 0 and repeatedly apply the function then we can do a
377-- bubble sort.
378foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
379foldbWith level f = undefined
380-}
382-- XXX consider the bulk update/accumulation/permutation APIs from vector.
384-------------------------------------------------------------------------------
385-- Random reads and writes
386-------------------------------------------------------------------------------
388-- | /O(1)/ Lookup the element at the given index, starting from 0.
389--
390-- /Internal/
391{-# INLINE readIndex #-}
392readIndex :: Storable a => Array a -> Int -> Maybe a
393readIndex arr i =
394 if i < 0 || i > length arr - 1
395 then Nothing
396 else A.unsafeInlineIO $
397 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
399{-
400-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
401-- at index @i@ and reading up to @count@ elements in the forward direction
402-- ending at the index @i + count - 1@.
403--
404-- @since 0.7.0
405{-# INLINE readSlice #-}
406readSlice :: (IsStream t, Monad m, Storable a)
407 => Array a -> Int -> Int -> t m a
408readSlice arr i len = undefined
410-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
411-- index @i@ and reading up to @count@ elements in the reverse direction ending
412-- at the index @i - count + 1@.
413--
414-- @since 0.7.0
415{-# INLINE readSliceRev #-}
416readSliceRev :: (IsStream t, Monad m, Storable a)
417 => Array a -> Int -> Int -> t m a
418readSliceRev arr i len = undefined
419-}
421-- | /O(1)/ Write the given element at the given index in the array.
422-- Performs in-place mutation of the array.
423--
424-- /Internal/
425{-# INLINE writeIndex #-}
426writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
427writeIndex arr i a = do
428 let maxIndex = length arr - 1
429 if i < 0
430 then error "writeIndex: negative array index"
431 else if i > maxIndex
432 then error $ "writeIndex: specified array index " ++ show i
433 ++ " is beyond the maximum index " ++ show maxIndex
434 else
435 liftIO $ withForeignPtr (aStart arr) $ \p ->
436 pokeElemOff p i a
438{-
439-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
440-- starting at index @i@ and writing up to @count@ elements in the forward
441-- direction ending at the index @i + count - 1@.
442--
443-- @since 0.7.0
444{-# INLINE writeSlice #-}
445writeSlice :: (IsStream t, Monad m, Storable a)
446 => Array a -> Int -> Int -> t m a -> m (Array a)
447writeSlice arr i len s = undefined
449-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
450-- starting at index @i@ and writing up to @count@ elements in the reverse
451-- direction ending at the index @i - count + 1@.
452--
453-- @since 0.7.0
454{-# INLINE writeSliceRev #-}
455writeSliceRev :: (IsStream t, Monad m, Storable a)
456 => Array a -> Int -> Int -> t m a -> m (Array a)
457writeSliceRev arr i len s = undefined
458-}
460-------------------------------------------------------------------------------
461-- Transform via stream operations
462-------------------------------------------------------------------------------
464-- for non-length changing operations we can use the original length for
465-- allocation. If we can predict the length then we can use the prediction for
466-- new allocation. Otherwise we can use a hint and adjust dynamically.
468{-
469-- | Transform an array into another array using a pipe transformation
470-- operation.
471--
472-- @since 0.7.0
473{-# INLINE runPipe #-}
474runPipe :: (MonadIO m, Storable a, Storable b)
475 => Pipe m a b -> Array a -> m (Array b)
476runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
477-}
479-- | Transform an array into another array using a stream transformation
480-- operation.
481--
482-- /Internal/
483{-# INLINE streamTransform #-}
484streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
485 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
486streamTransform f arr =
487 P.foldOnce (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
488 $ f (A.toStream arr)
490-------------------------------------------------------------------------------
491-- Casts
492-------------------------------------------------------------------------------
494-- | Cast an array having elements of type @a@ into an array having elements of
495-- type @b@. The array size must be a multiple of the size of type @b@
496-- otherwise accessing the last element of the array may result into a crash or
497-- a random value.
498--
499-- /Internal/
500--
501unsafeCast ::
502#ifdef DEVBUILD
503 Storable b =>
504#endif
505 Array a -> Array b
506unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
508-- | Cast an array into a Word8 array
509--
510-- /Internal/
511--
512asByteArray :: Array a -> Array Word8
513asByteArray = unsafeCast
515-- | Cast an array having elements of type @a@ into an array having elements of
516-- type @b@. The length of the array should be a multiple of the size of the
517-- target element otherwise 'Nothing' is returned.
518--
519-- /Internal/
520--
521cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
522cast arr =
523 let len = A.byteLength arr
524 r = len `mod` sizeOf (undefined :: b)
525 in if r /= 0
526 then Nothing
527 else Just $ unsafeCast arr
529-- | Use an @Array a@ as @Ptr b@.
530--
531-- /Unsafe/
532--
533-- /Internal/
534--
535asPtr :: Array a -> (Ptr b -> IO c) -> IO c
536asPtr Array{..} act = do
537 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
539-- | Convert an array of any type into a null terminated CString Ptr.
540--
541-- /Unsafe/
542--
543-- /O(n) Time: (creates a copy of the array)/
544--
545-- /Internal/
546--
547asCString :: Array a -> (CString -> IO b) -> IO b
548asCString arr act = do
549 let Array{..} = asByteArray arr <> A.fromList [0]
550 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
552-------------------------------------------------------------------------------
553-- Folds
554-------------------------------------------------------------------------------
556-- | Fold an array using a 'Fold'.
557--
558-- /Internal/
559{-# INLINE fold #-}
560fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
561fold f arr = P.foldOnce f (A.toStream arr :: Serial.SerialT m a)
563-- | Fold an array using a stream fold operation.
564--
565-- /Internal/
566{-# INLINE streamFold #-}
567streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
568streamFold f arr = f (A.toStream arr)