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)
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
97 -- , writeFrom -- start writing at the given position
99 -- , writeTo -- write from beginning up to the given position
104 -- , writeChunksOfFrom
118 -- -- * In-pace mutation (for Mutable Array type)
124 -- * Immutable Transformations
138 -- * Folds with Array as the container
143import Control.Monad (when)
144import Control.Monad.IO.Class (MonadIO(..))
145#if !(MIN_VERSION_base(4,11,0))
146import Data.Semigroup ((<>))
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-------------------------------------------------------------------------------
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.
187{-# INLINE fromStreamN #-}
188fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
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.
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.
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-------------------------------------------------------------------------------
209-------------------------------------------------------------------------------
211-- | Unfold an array into a stream.
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.
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.
233{-# INLINE_NORMAL unsafeRead #-}
234unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
235unsafeRead = Unfold step inject
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.
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
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
261null :: Storable a => Array a -> Bool
262null arr = length arr == 0
264-- | > last arr = readIndex arr (length arr - 1)
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.
277lastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
279 | n <= 0 = fmap (const mempty) FL.drain
280 | otherwise = A.unsafeFreeze <$> Fold step initial done
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)
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
293 | i < n = RB.unsafeFoldRingM
294 | otherwise = RB.unsafeFoldRingFullM
296-------------------------------------------------------------------------------
298-------------------------------------------------------------------------------
300-------------------------------------------------------------------------------
302-------------------------------------------------------------------------------
305-- | Perform a binary search in the array to find an element.
306bsearch :: a -> Array a -> Maybe Bool
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
320findIndex :: (a -> Bool) -> Array a -> Maybe Int
323findIndices :: (a -> Bool) -> Array a -> Array Int
324findIndices = undefined
327-------------------------------------------------------------------------------
329-------------------------------------------------------------------------------
331-- XXX We can potentially use SIMD instructions on arrays to fold faster.
333-------------------------------------------------------------------------------
335-------------------------------------------------------------------------------
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
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.
369-- | Perform a top down hierarchical recursive partitioning fold of items in
370-- the container using the given function as the partition function.
372-- This will perform a quick sort if the partition function is
373-- 'partitionBy (< pivot)'.
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.
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
386foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
387foldbWith level f = undefined
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.
399{-# INLINE readIndex #-}
400readIndex :: Storable a => Array a -> Int -> Maybe a
402 if i < 0 || i > length arr - 1
404 else A.unsafeInlineIO $
405 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
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@.
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@.
423{-# INLINE readSliceRev #-}
424readSliceRev :: (IsStream t, Monad m, Storable a)
425 => Array a -> Int -> Int -> t m a
426readSliceRev arr i len = undefined
429-- | /O(1)/ Write the given element at the given index in the array.
430-- Performs in-place mutation of the array.
433{-# INLINE writeIndex #-}
434writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
435writeIndex arr i a = do
436 let maxIndex = length arr - 1
438 then error "writeIndex: negative array index"
440 then error $ "writeIndex: specified array index " ++ show i
441 ++ " is beyond the maximum index " ++ show maxIndex
443 liftIO $ withForeignPtr (aStart arr) $ \p ->
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@.
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@.
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
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.
477-- | Transform an array into another array using a pipe transformation
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)
487-- | Transform an array into another array using a stream transformation
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))
498-------------------------------------------------------------------------------
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
514unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
516-- | Cast an array into a Word8 array
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.
529cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
531 let len = A.byteLength arr
532 r = len `mod` sizeOf (undefined :: b)
535 else Just $ unsafeCast arr
537-- | Use an @Array a@ as @Ptr b@.
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.
551-- /O(n) Time: (creates a copy of the array)/
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-------------------------------------------------------------------------------
562-------------------------------------------------------------------------------
564-- | Fold an array using a '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.
574{-# INLINE streamFold #-}
575streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
576streamFold 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