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
41 -- Pure, From Static Memory (Unsafe)
42 -- We can use fromPtrM#, fromCStringM# and fromAddrM# to create arrays from
43 -- a dynamic memory address which requires a finalizer.
57 , A.writeN -- drop new
59 , A.write -- full buffer
67 , unsafeRead -- XXX readUnsafe?
69 , producer -- experimental
74 , A.unsafeIndex -- XXX Rename to getIndexUnsafe??
76 , last -- XXX getIndexLast?
78 , getIndicesFromThenTo
79 -- , getIndicesFrom -- read from a given position to the end of file
80 -- , getIndicesUpto -- read from beginning up to the given position
82 -- , getIndicesFromRev -- read from a given position to the beginning of file
83 -- , getIndicesUptoRev -- read from end to the given position in file
98 , unsafeCast -- castUnsafe?
99 , unsafeAsPtr -- asPtrUnsafe?
100 , unsafeAsCString -- asCStringUnsafe?
101 , A.unsafeFreeze -- asImmutableUnsafe?
102 , A.unsafeThaw -- asMutableUnsafe?
111 -- * Streaming Operations
120import Control.Exception (assert)
121import Control.Monad (when)
122import Control.Monad.IO.Class (MonadIO(..))
123import Data.Functor.Identity (Identity)
124#if !(MIN_VERSION_base(4,11,0))
125import Data.Semigroup ((<>))
127import Data.Word (Word8)
128import Foreign.C.String (CString)
129import Foreign.ForeignPtr (castForeignPtr)
130import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
131import Foreign.Ptr (plusPtr, castPtr)
132import Foreign.Storable (Storable(..))
133import Prelude hiding (length, null, last, map, (!!), read, concat)
135import GHC.ForeignPtr (ForeignPtr(..))
136import GHC.Ptr (Ptr(..))
137import GHC.Prim (touch#)
138import GHC.IO (IO(..))
140import Streamly.Internal.BaseCompat
141import Streamly.Internal.Data.Array.Foreign.Type (Array(..), length)
142import Streamly.Internal.Data.Fold.Type (Fold(..))
143import Streamly.Internal.Data.Producer.Type (Producer)
144import Streamly.Internal.Data.Stream.Serial (SerialT(..))
145import Streamly.Internal.Data.Tuple.Strict (Tuple3'(..))
146import Streamly.Internal.Data.Unfold.Type (Unfold(..))
147import Streamly.Internal.System.IO (unsafeInlineIO)
149import qualified Streamly.Internal.Data.Array.Foreign.Mut.Type as MA
150import qualified Streamly.Internal.Data.Array.Foreign.Mut as MA
151import qualified Streamly.Internal.Data.Array.Foreign.Type as A
152import qualified Streamly.Internal.Data.Fold as FL
153import qualified Streamly.Internal.Data.Stream.Prelude as P
154import qualified Streamly.Internal.Data.Stream.StreamD as D
155import qualified Streamly.Internal.Data.Unfold as Unfold
156import qualified Streamly.Internal.Data.Producer.Type as Producer
157import qualified Streamly.Internal.Ring.Foreign as RB
159#if MIN_VERSION_base(4,10,0)
160import Foreign.ForeignPtr (plusForeignPtr)
162import GHC.Base (Int(..), plusAddr#)
163import GHC.ForeignPtr (ForeignPtr(..))
164plusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b
165plusForeignPtr (ForeignPtr addr c) (I# d) = ForeignPtr (plusAddr# addr d) c
168-------------------------------------------------------------------------------
170-------------------------------------------------------------------------------
172-- | Create an 'Array' from the first N elements of a stream. The array is
173-- allocated to size N, if the stream terminates before N elements then the
174-- array may hold less than N elements.
177{-# INLINE fromStreamN #-}
178fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
179fromStreamN n (SerialT m) = do
180 when (n < 0) $ error "writeN: negative write count specified"
181 A.fromStreamDN n $ D.fromStreamK m
183-- | Create an 'Array' from a stream. This is useful when we want to create a
184-- single array from a stream of unknown size. 'writeN' is at least twice
185-- as efficient when the size is already known.
187-- Note that if the input stream is too large memory allocation for the array
188-- may fail. When the stream size is not known, `arraysOf` followed by
189-- processing of indvidual arrays in the resulting stream should be preferred.
192{-# INLINE fromStream #-}
193fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
194fromStream (SerialT m) = P.fold A.write m
195-- write m = A.fromStreamD $ D.fromStreamK m
197-------------------------------------------------------------------------------
199-------------------------------------------------------------------------------
201-- | Unfold an array into a stream.
203-- /Since 0.7.0 (Streamly.Memory.Array)/
206{-# INLINE_NORMAL read #-}
207read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
208read = Unfold.lmap A.unsafeThaw MA.read
210{-# INLINE_NORMAL producer #-}
211producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
212producer = Producer.translate A.unsafeThaw A.unsafeFreeze MA.producer
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 = 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', () #)
251-- >>> import qualified Streamly.Internal.Data.Array.Foreign.Type as Array
252-- >>> null arr = Array.byteLength arr == 0
256null :: Array a -> Bool
257null arr = A.byteLength arr == 0
259-- | Like 'getIndex' but indexes the array in reverse from the end.
262{-# INLINE getIndexRev #-}
263getIndexRev :: forall a. Storable a => Array a -> Int -> Maybe a
266 unsafeWithForeignPtr (aStart arr) $ \ptr -> do
267 let elemSize = sizeOf (undefined :: a)
268 elemPtr = aEnd arr `plusPtr` negate (elemSize * (i + 1))
269 if i >= 0 && elemPtr >= ptr
270 then Just <$> peek elemPtr
275-- >>> import qualified Streamly.Internal.Data.Array.Foreign as Array
276-- >>> last arr = Array.getIndexRev arr 0
280last :: Storable a => Array a -> Maybe a
281last arr = getIndexRev arr 0
283-------------------------------------------------------------------------------
284-- Folds with Array as the container
285-------------------------------------------------------------------------------
287-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
288-- stream to an 'Array'.
291{-# INLINE writeLastN #-}
292writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
294 | n <= 0 = fmap (const mempty) FL.drain
295 | otherwise = A.unsafeFreeze <$> Fold step initial done
299 step (Tuple3' rb rh i) a = do
300 rh1 <- liftIO $ RB.unsafeInsert rb rh a
301 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
304 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
305 in fmap f $ liftIO $ RB.new n
307 done (Tuple3' rb rh i) = do
308 arr <- liftIO $ MA.newArray n
309 foldFunc i rh snoc' arr rb
311 -- XXX We should write a read unfold for ring.
312 snoc' b a = liftIO $ MA.snocUnsafe b a
315 | i < n = RB.unsafeFoldRingM
316 | otherwise = RB.unsafeFoldRingFullM
318-------------------------------------------------------------------------------
320-------------------------------------------------------------------------------
322-------------------------------------------------------------------------------
324-------------------------------------------------------------------------------
326-- | Given a sorted array, perform a binary search to find the given element.
327-- Returns the index of the element if found.
330{-# INLINE binarySearch #-}
331binarySearch :: a -> Array a -> Maybe Int
332binarySearch = undefined
334-- find/findIndex etc can potentially be implemented more efficiently on arrays
335-- compared to streams by using SIMD instructions.
336-- We can also return a bit array instead.
338-- | Perform a linear search to find all the indices where a given element is
339-- present in an array.
342findIndicesOf :: (a -> Bool) -> Unfold Identity (Array a) Int
343findIndicesOf = undefined
346findIndexOf :: (a -> Bool) -> Array a -> Maybe Int
347findIndexOf p = Unfold.fold Fold.head . Stream.unfold (findIndicesOf p)
349find :: (a -> Bool) -> Array a -> Bool
350find = Unfold.fold Fold.null . Stream.unfold (findIndicesOf p)
353-------------------------------------------------------------------------------
355-------------------------------------------------------------------------------
357-- XXX We can potentially use SIMD instructions on arrays to fold faster.
359-------------------------------------------------------------------------------
361-------------------------------------------------------------------------------
363-- | /O(1)/ Slice an array in constant time.
365-- Caution: The bounds of the slice are not checked.
370{-# INLINE getSliceUnsafe #-}
373 => Int -- ^ starting index
374 -> Int -- ^ length of the slice
377getSliceUnsafe index len (Array fp e) =
378 let size = sizeOf (undefined :: a)
379 fp1 = fp `plusForeignPtr` (index * size)
380 end = unsafeForeignPtrToPtr fp1 `plusPtr` (len * size)
381 in assert (end <= e) (Array fp1 end)
383-- | Split the array into a stream of slices using a predicate. The element
384-- matching the predicate is dropped.
387{-# INLINE splitOn #-}
388splitOn :: (Monad m, Storable a) =>
389 (a -> Bool) -> Array a -> SerialT m (Array a)
390splitOn predicate arr =
391 fmap A.unsafeFreeze $ MA.splitOn predicate (A.unsafeThaw arr)
393{-# INLINE genSlicesFromLen #-}
394genSlicesFromLen :: forall m a. (Monad m, Storable a)
395 => Int -- ^ from index
396 -> Int -- ^ length of the slice
397 -> Unfold m (Array a) (Int, Int)
398genSlicesFromLen from len =
399 Unfold.lmap A.unsafeThaw (MA.genSlicesFromLen from len)
401-- | Generate a stream of slices of specified length from an array, starting
402-- from the supplied array index. The last slice may be shorter than the
406{-# INLINE getSlicesFromLen #-}
407getSlicesFromLen :: forall m a. (Monad m, Storable a)
408 => Int -- ^ from index
409 -> Int -- ^ length of the slice
410 -> Unfold m (Array a) (Array a)
411getSlicesFromLen from len =
413 $ Unfold.lmap A.unsafeThaw (MA.getSlicesFromLen from len)
415-------------------------------------------------------------------------------
416-- Random reads and writes
417-------------------------------------------------------------------------------
419-- XXX Change this to a partial function instead of a Maybe type? And use
420-- MA.getIndex instead.
422-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
425{-# INLINE getIndex #-}
426getIndex :: forall a. Storable a => Array a -> Int -> Maybe a
429 unsafeWithForeignPtr (aStart arr) $ \ptr -> do
430 let elemSize = sizeOf (undefined :: a)
431 elemPtr = ptr `plusPtr` (elemSize * i)
432 if i >= 0 && elemPtr `plusPtr` elemSize <= aEnd arr
433 then Just <$> peek elemPtr
436-- | Given a stream of array indices, read the elements on those indices from
437-- the supplied Array. An exception is thrown if an index is out of bounds.
439-- This is the most general operation. We can implement other operations in
444-- let u = lmap (\arr -> (0, length arr - 1)) Unfold.enumerateFromTo
445-- in Unfold.lmap f (getIndices arr)
448-- let i = length arr - 1
449-- in Unfold.lmap f (getIndicesFromThenTo i (i - 1) 0)
453{-# INLINE getIndices #-}
454getIndices :: Unfold m (Array a) Int -> Unfold m (Array a) a
455getIndices = undefined
457-- | Unfolds @(from, then, to, array)@ generating a finite stream whose first
458-- element is the array value from the index @from@ and the successive elements
459-- are from the indices in increments of @then@ up to @to@. Index enumeration
460-- can occur downwards or upwards depending on whether @then@ comes before or
464-- getIndicesFromThenTo =
465-- let f (from, next, to, arr) =
466-- (Stream.enumerateFromThenTo from next to, arr)
467-- in Unfold.lmap f getIndices
471{-# INLINE getIndicesFromThenTo #-}
472getIndicesFromThenTo :: Unfold m (Int, Int, Int, Array a) a
473getIndicesFromThenTo = undefined
475-------------------------------------------------------------------------------
476-- Transform via stream operations
477-------------------------------------------------------------------------------
479-- for non-length changing operations we can use the original length for
480-- allocation. If we can predict the length then we can use the prediction for
481-- new allocation. Otherwise we can use a hint and adjust dynamically.
484-- | Transform an array into another array using a pipe transformation
488{-# INLINE runPipe #-}
489runPipe :: (MonadIO m, Storable a, Storable b)
490 => Pipe m a b -> Array a -> m (Array b)
491runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
494-- XXX For transformations that cannot change the number of elements e.g. "map"
495-- we can use a predetermined array length.
497-- | Transform an array into another array using a stream transformation
501{-# INLINE streamTransform #-}
502streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
503 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
504streamTransform f arr =
505 P.fold (A.writeWith (length arr)) $ getSerialT $ f (A.toStream arr)
507-------------------------------------------------------------------------------
509-------------------------------------------------------------------------------
511-- | Cast an array having elements of type @a@ into an array having elements of
512-- type @b@. The array size must be a multiple of the size of type @b@
513-- otherwise accessing the last element of the array may result into a crash or
523unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
525-- | Cast an @Array a@ into an @Array Word8@.
529asBytes :: Array a -> Array Word8
532-- | Cast an array having elements of type @a@ into an array having elements of
533-- type @b@. The length of the array should be a multiple of the size of the
534-- target element otherwise 'Nothing' is returned.
538cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
540 let len = A.byteLength arr
541 r = len `mod` sizeOf (undefined :: b)
544 else Just $ unsafeCast arr
546-- | Use an @Array a@ as @Ptr b@.
552unsafeAsPtr :: Array a -> (Ptr b -> IO c) -> IO c
553unsafeAsPtr Array{..} act = do
554 unsafeWithForeignPtr aStart $ \ptr -> act (castPtr ptr)
556-- | Convert an array of any type into a null terminated CString Ptr.
560-- /O(n) Time: (creates a copy of the array)/
564unsafeAsCString :: Array a -> (CString -> IO b) -> IO b
565unsafeAsCString arr act = do
566 let Array{..} = asBytes arr <> A.fromList [0]
567 unsafeWithForeignPtr aStart $ \ptr -> act (castPtr ptr)
569-------------------------------------------------------------------------------
571-------------------------------------------------------------------------------
573-- | Fold an array using a 'Fold'.
577fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
578fold f arr = P.fold f (getSerialT (A.toStream arr))
580-- | Fold an array using a stream fold operation.
583{-# INLINE streamFold #-}
584streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
585streamFold 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