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
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)
126 -- * Immutable Transformations
142import Control.Monad (when)
143import Control.Monad.IO.Class (MonadIO(..))
144#if !(MIN_VERSION_base(4,11,0))
145import Data.Semigroup ((<>))
147import Data.Word (Word8)
148-- import Data.Functor.Identity (Identity)
149import Foreign.C.String (CString)
150import Foreign.ForeignPtr (withForeignPtr, castForeignPtr)
151import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
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.Type (Array(..), length)
162import Streamly.Internal.Data.Fold.Type (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.Type (Unfold(..))
168import qualified Streamly.Internal.Data.Array.Foreign.Mut.Type as MA
169import qualified Streamly.Internal.Data.Array.Foreign.Type 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#if MIN_VERSION_base(4,10,0)
179import Foreign.ForeignPtr (plusForeignPtr)
181import GHC.Base (Int(..), plusAddr#)
182import GHC.ForeignPtr (ForeignPtr(..))
183plusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b
184plusForeignPtr (ForeignPtr addr c) (I# d) = ForeignPtr (plusAddr# addr d) c
187-------------------------------------------------------------------------------
189-------------------------------------------------------------------------------
191-- | Create an 'Array' from the first N elements of a stream. The array is
192-- allocated to size N, if the stream terminates before N elements then the
193-- array may hold less than N elements.
196{-# INLINE fromStreamN #-}
197fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
199 when (n < 0) $ error "writeN: negative write count specified"
200 A.fromStreamDN n $ D.toStreamD m
202-- | Create an 'Array' from a stream. This is useful when we want to create a
203-- single array from a stream of unknown size. 'writeN' is at least twice
204-- as efficient when the size is already known.
206-- Note that if the input stream is too large memory allocation for the array
207-- may fail. When the stream size is not known, `arraysOf` followed by
208-- processing of indvidual arrays in the resulting stream should be preferred.
211{-# INLINE fromStream #-}
212fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
213fromStream = P.fold A.write
214-- write m = A.fromStreamD $ D.toStreamD m
216-------------------------------------------------------------------------------
218-------------------------------------------------------------------------------
220-- | Unfold an array into a stream.
223{-# INLINE_NORMAL read #-}
224read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
225read = Unfold.lmap A.unsafeThaw MA.read
227{-# INLINE_NORMAL producer #-}
228producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
229producer = Producer.translate A.unsafeThaw A.unsafeFreeze MA.producer
231-- | Unfold an array into a stream, does not check the end of the array, the
232-- user is responsible for terminating the stream within the array bounds. For
233-- high performance application where the end condition can be determined by
234-- a terminating fold.
236-- Written in the hope that it may be faster than "read", however, in the case
237-- for which this was written, "read" proves to be faster even though the core
238-- generated with unsafeRead looks simpler.
242{-# INLINE_NORMAL unsafeRead #-}
243unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
244unsafeRead = Unfold step inject
247 inject (Array fp _) = return fp
249 {-# INLINE_LATE step #-}
250 step (ForeignPtr p contents) = do
251 -- unsafeInlineIO allows us to run this in Identity monad for pure
252 -- toList/foldr case which makes them much faster due to not
253 -- accumulating the list and fusing better with the pure consumers.
255 -- This should be safe as the array contents are guaranteed to be
256 -- evaluated/written to before we peek at them.
257 let !x = A.unsafeInlineIO $ do
261 let !(Ptr p1) = Ptr p `plusPtr` sizeOf (undefined :: a)
262 return $ D.Yield x (ForeignPtr p1 contents)
264 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
266-- | > null arr = length arr == 0
270null :: Storable a => Array a -> Bool
271null arr = length arr == 0
273-- | > last arr = getIndex arr (length arr - 1)
277last :: Storable a => Array a -> Maybe a
278last arr = getIndex arr (length arr - 1)
280-------------------------------------------------------------------------------
281-- Folds with Array as the container
282-------------------------------------------------------------------------------
284-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
285-- stream to an 'Array'.
288{-# INLINE writeLastN #-}
289writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
291 | n <= 0 = fmap (const mempty) FL.drain
292 | otherwise = A.unsafeFreeze <$> Fold step initial done
296 step (Tuple3' rb rh i) a = do
297 rh1 <- liftIO $ RB.unsafeInsert rb rh a
298 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
301 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
302 in fmap f $ liftIO $ RB.new n
304 done (Tuple3' rb rh i) = do
305 arr <- liftIO $ MA.newArray n
306 foldFunc i rh snoc' arr rb
308 snoc' b a = liftIO $ MA.unsafeSnoc b a
311 | i < n = RB.unsafeFoldRingM
312 | otherwise = RB.unsafeFoldRingFullM
314-------------------------------------------------------------------------------
316-------------------------------------------------------------------------------
318-------------------------------------------------------------------------------
320-------------------------------------------------------------------------------
323-- | Perform a binary search in the array to find an element.
324bsearch :: a -> Array a -> Maybe Bool
327-- | Perform a binary search in the array to find an element index.
328{-# INLINE elemIndex #-}
329bsearchIndex :: a -> Array a -> Maybe Int
330bsearchIndex elem arr = undefined
332-- find/findIndex etc can potentially be implemented more efficiently on arrays
333-- compared to streams by using SIMD instructions.
335find :: (a -> Bool) -> Array a -> Bool
338findIndex :: (a -> Bool) -> Array a -> Maybe Int
341findIndices :: (a -> Bool) -> Array a -> Array Int
342findIndices = undefined
345-------------------------------------------------------------------------------
347-------------------------------------------------------------------------------
349-- XXX We can potentially use SIMD instructions on arrays to fold faster.
351-------------------------------------------------------------------------------
353-------------------------------------------------------------------------------
355-- | /O(1)/ Slice an array in constant time.
357-- Caution: The bounds of the slice are not checked.
362{-# INLINE unsafeSlice #-}
365 => Int -- ^ starting index
366 -> Int -- ^ length of the slice
369unsafeSlice start len (Array fp _) =
370 let size = sizeOf (undefined :: a)
371 fp1 = fp `plusForeignPtr` (start * size)
372 end = unsafeForeignPtrToPtr fp1 `plusPtr` (len * size)
377splitAt :: Int -> Array a -> (Array a, Array a)
378splitAt i arr = undefined
380-- XXX This operation can be performed efficiently via streams.
381-- | Append two arrays together to create a single array.
382splice :: Array a -> Array a -> Array a
383splice arr1 arr2 = undefined
385-------------------------------------------------------------------------------
386-- In-place mutation APIs
387-------------------------------------------------------------------------------
389-- | Partition an array into two halves using a partitioning predicate. The
390-- first half retains values where the predicate is 'False' and the second half
391-- retains values where the predicate is 'True'.
392{-# INLINE partitionBy #-}
393partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
394partitionBy f arr = undefined
396-- | Shuffle corresponding elements from two arrays using a shuffle function.
397-- If the shuffle function returns 'False' then do nothing otherwise swap the
398-- elements. This can be used in a bottom up fold to shuffle or reorder the
400shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
401shuffleBy f arr1 arr2 = undefined
403-- XXX we can also make the folds partial by stopping at a certain level.
405-- | Perform a top down hierarchical recursive partitioning fold of items in
406-- the container using the given function as the partition function.
408-- This will perform a quick sort if the partition function is
409-- 'partitionBy (< pivot)'.
412{-# INLINABLE foldtWith #-}
413foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
414foldtWith level f = undefined
416-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
417-- indicates the level in the tree where the fold would stop.
419-- This will perform a random shuffle if the shuffle function is random.
420-- If we stop at level 0 and repeatedly apply the function then we can do a
422foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
423foldbWith level f = undefined
426-- XXX consider the bulk update/accumulation/permutation APIs from vector.
428-------------------------------------------------------------------------------
429-- Random reads and writes
430-------------------------------------------------------------------------------
432-- | /O(1)/ Lookup the element at the given index, starting from 0.
435{-# INLINE getIndex #-}
436getIndex :: Storable a => Array a -> Int -> Maybe a
438 if i < 0 || i > length arr - 1
440 else A.unsafeInlineIO $
441 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
444-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
445-- at index @i@ and reading up to @count@ elements in the forward direction
446-- ending at the index @i + count - 1@.
449{-# INLINE readSlice #-}
450readSlice :: (IsStream t, Monad m, Storable a)
451 => Array a -> Int -> Int -> t m a
452readSlice arr i len = undefined
454-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
455-- index @i@ and reading up to @count@ elements in the reverse direction ending
456-- at the index @i - count + 1@.
459{-# INLINE readSliceRev #-}
460readSliceRev :: (IsStream t, Monad m, Storable a)
461 => Array a -> Int -> Int -> t m a
462readSliceRev arr i len = undefined
465-- | /O(1)/ Write the given element at the given index in the array.
466-- Performs in-place mutation of the array.
469{-# INLINE writeIndex #-}
470writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
471writeIndex arr i a = do
472 let maxIndex = length arr - 1
474 then error "writeIndex: negative array index"
476 then error $ "writeIndex: specified array index " ++ show i
477 ++ " is beyond the maximum index " ++ show maxIndex
479 liftIO $ withForeignPtr (aStart arr) $ \p ->
483-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
484-- starting at index @i@ and writing up to @count@ elements in the forward
485-- direction ending at the index @i + count - 1@.
488{-# INLINE writeSlice #-}
489writeSlice :: (IsStream t, Monad m, Storable a)
490 => Array a -> Int -> Int -> t m a -> m (Array a)
491writeSlice arr i len s = undefined
493-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
494-- starting at index @i@ and writing up to @count@ elements in the reverse
495-- direction ending at the index @i - count + 1@.
498{-# INLINE writeSliceRev #-}
499writeSliceRev :: (IsStream t, Monad m, Storable a)
500 => Array a -> Int -> Int -> t m a -> m (Array a)
501writeSliceRev arr i len s = undefined
504-------------------------------------------------------------------------------
505-- Transform via stream operations
506-------------------------------------------------------------------------------
508-- for non-length changing operations we can use the original length for
509-- allocation. If we can predict the length then we can use the prediction for
510-- new allocation. Otherwise we can use a hint and adjust dynamically.
513-- | Transform an array into another array using a pipe transformation
517{-# INLINE runPipe #-}
518runPipe :: (MonadIO m, Storable a, Storable b)
519 => Pipe m a b -> Array a -> m (Array b)
520runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
523-- | Transform an array into another array using a stream transformation
527{-# INLINE streamTransform #-}
528streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
529 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
530streamTransform f arr =
531 P.fold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
534-------------------------------------------------------------------------------
536-------------------------------------------------------------------------------
538-- | Cast an array having elements of type @a@ into an array having elements of
539-- type @b@. The array size must be a multiple of the size of type @b@
540-- otherwise accessing the last element of the array may result into a crash or
550unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
552-- | Cast an @Array a@ into an @Array Word8@.
556asBytes :: Array a -> Array Word8
559-- | Cast an array having elements of type @a@ into an array having elements of
560-- type @b@. The length of the array should be a multiple of the size of the
561-- target element otherwise 'Nothing' is returned.
565cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
567 let len = A.byteLength arr
568 r = len `mod` sizeOf (undefined :: b)
571 else Just $ unsafeCast arr
573-- | Use an @Array a@ as @Ptr b@.
579asPtr :: Array a -> (Ptr b -> IO c) -> IO c
580asPtr Array{..} act = do
581 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
583-- | Convert an array of any type into a null terminated CString Ptr.
587-- /O(n) Time: (creates a copy of the array)/
591asCString :: Array a -> (CString -> IO b) -> IO b
592asCString arr act = do
593 let Array{..} = asBytes arr <> A.fromList [0]
594 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
596-------------------------------------------------------------------------------
598-------------------------------------------------------------------------------
600-- | Fold an array using a 'Fold'.
604fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
605fold f arr = P.fold f (A.toStream arr :: Serial.SerialT m a)
607-- | Fold an array using a stream fold operation.
610{-# INLINE streamFold #-}
611streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
612streamFold 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