1{-# LANGUAGE UnboxedTuples #-}
6-- Module : Streamly.Internal.Data.Array.Foreign
7-- Copyright : (c) 2019 Composewell Technologies
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
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
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
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
35module Streamly.Internal.Data.Array.Foreign
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.
60 , A.writeN -- drop new
62 , A.write -- full buffer
63 -- , writeLastN -- drop old (ring buffer)
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
95 -- , writeFrom -- start writing at the given position
97 -- , writeTo -- write from beginning up to the given position
102 -- , writeChunksOfFrom
116 -- -- * In-pace mutation (for Mutable Array type)
122 -- * Immutable Transformations
136 -- * Folds with Array as the container
141import Control.Monad (when)
142import Control.Monad.IO.Class (MonadIO(..))
143#if !(MIN_VERSION_base(4,11,0))
144import Data.Semigroup ((<>))
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-------------------------------------------------------------------------------
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.
183{-# INLINE fromStreamN #-}
184fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
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.
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.
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-------------------------------------------------------------------------------
205-------------------------------------------------------------------------------
207-- | Unfold an array into a stream.
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.
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.
225{-# INLINE_NORMAL unsafeRead #-}
226unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
227unsafeRead = Unfold step inject
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.
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
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
253null :: Storable a => Array a -> Bool
254null arr = length arr == 0
256-- | > last arr = readIndex arr (length arr - 1)
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.
269lastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
271 | n <= 0 = fmap (const mempty) FL.drain
272 | otherwise = A.unsafeFreeze <$> Fold step initial done
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)
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
285 | i < n = RB.unsafeFoldRingM
286 | otherwise = RB.unsafeFoldRingFullM
288-------------------------------------------------------------------------------
290-------------------------------------------------------------------------------
292-------------------------------------------------------------------------------
294-------------------------------------------------------------------------------
297-- | Perform a binary search in the array to find an element.
298bsearch :: a -> Array a -> Maybe Bool
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
312findIndex :: (a -> Bool) -> Array a -> Maybe Int
315findIndices :: (a -> Bool) -> Array a -> Array Int
316findIndices = undefined
319-------------------------------------------------------------------------------
321-------------------------------------------------------------------------------
323-- XXX We can potentially use SIMD instructions on arrays to fold faster.
325-------------------------------------------------------------------------------
327-------------------------------------------------------------------------------
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
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.
361-- | Perform a top down hierarchical recursive partitioning fold of items in
362-- the container using the given function as the partition function.
364-- This will perform a quick sort if the partition function is
365-- 'partitionBy (< pivot)'.
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.
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
378foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
379foldbWith level f = undefined
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.
391{-# INLINE readIndex #-}
392readIndex :: Storable a => Array a -> Int -> Maybe a
394 if i < 0 || i > length arr - 1
396 else A.unsafeInlineIO $
397 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
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@.
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@.
415{-# INLINE readSliceRev #-}
416readSliceRev :: (IsStream t, Monad m, Storable a)
417 => Array a -> Int -> Int -> t m a
418readSliceRev arr i len = undefined
421-- | /O(1)/ Write the given element at the given index in the array.
422-- Performs in-place mutation of the array.
425{-# INLINE writeIndex #-}
426writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
427writeIndex arr i a = do
428 let maxIndex = length arr - 1
430 then error "writeIndex: negative array index"
432 then error $ "writeIndex: specified array index " ++ show i
433 ++ " is beyond the maximum index " ++ show maxIndex
435 liftIO $ withForeignPtr (aStart arr) $ \p ->
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@.
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@.
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
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.
469-- | Transform an array into another array using a pipe transformation
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)
479-- | Transform an array into another array using a stream transformation
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))
490-------------------------------------------------------------------------------
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
506unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
508-- | Cast an array into a Word8 array
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.
521cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
523 let len = A.byteLength arr
524 r = len `mod` sizeOf (undefined :: b)
527 else Just $ unsafeCast arr
529-- | Use an @Array a@ as @Ptr b@.
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.
543-- /O(n) Time: (creates a copy of the array)/
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-------------------------------------------------------------------------------
554-------------------------------------------------------------------------------
556-- | Fold an array using a '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.
566{-# INLINE streamFold #-}
567streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
568streamFold f arr = f (A.toStream arr)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list