2-- Module : Streamly.Internal.Data.Array.Foreign
3-- Copyright : (c) 2019 Composewell Technologies
6-- Maintainer : streamly@composewell.com
7-- Stability : experimental
12-- * Arrays are finite and fixed in size
13-- * provide /O(1)/ access to elements
14-- * store only data and not functions
15-- * provide efficient IO interfacing
17-- 'Foldable' instance is not provided because the implementation would be much
18-- less efficient compared to folding via streams. 'Semigroup' and 'Monoid'
19-- instances should be used with care; concatenating arrays using binary
20-- operations can be highly inefficient. Instead, use
21-- 'Streamly.Internal.Data.Array.Stream.Foreign.toArray' to concatenate N
24-- Each array is one pointer visible to the GC. Too many small arrays (e.g.
25-- single byte) are only as good as holding those elements in a Haskell list.
26-- However, small arrays can be compacted into large ones to reduce the
27-- overhead. To hold 32GB memory in 32k sized buffers we need 1 million arrays
28-- if we use one array for each chunk. This is still significant to add
31module Streamly.Internal.Data.Array.Foreign
37 -- Pure, From Static Memory (Unsafe)
38 -- We can use fromPtrM#, fromCStringM# and fromAddrM# to create arrays from
39 -- a dynamic memory address which requires a finalizer.
53 , A.writeN -- drop new
55 , A.write -- full buffer
63 , unsafeRead -- XXX readUnsafe?
65 , producer -- experimental
70 , A.unsafeIndex -- XXX Rename to getIndexUnsafe??
72 , last -- XXX getIndexLast?
74 , getIndicesFromThenTo
75 -- , getIndicesFrom -- read from a given position to the end of file
76 -- , getIndicesUpto -- read from beginning up to the given position
78 -- , getIndicesFromRev -- read from a given position to the beginning of file
79 -- , getIndicesUptoRev -- read from end to the given position in file
97 , A.unsafeFreeze -- asImmutableUnsafe?
98 , A.unsafeThaw -- asMutableUnsafe?
107 -- * Streaming Operations
117#include "ArrayMacros.h"
119import Control.Exception (assert)
120import Control.Monad (when)
121import Control.Monad.IO.Class (MonadIO(..))
122import Data.Functor.Identity (Identity)
123import Data.Word (Word8)
124import Foreign.C.String (CString)
125import Foreign.Ptr (plusPtr, castPtr)
126import Foreign.Storable (Storable(..))
127import Prelude hiding (length, null, last, map, (!!), read, concat)
129import Streamly.Internal.Data.Array.Foreign.Mut.Type (ReadUState(..), touch)
130import Streamly.Internal.Data.Array.Foreign.Type
131 (Array(..), length, asPtrUnsafe)
132import Streamly.Internal.Data.Fold.Type (Fold(..))
133import Streamly.Internal.Data.Producer.Type (Producer(..))
134import Streamly.Internal.Data.Stream.Serial (SerialT(..))
135import Streamly.Internal.Data.Tuple.Strict (Tuple3Fused'(..))
136import Streamly.Internal.Data.Unfold.Type (Unfold(..))
137import Streamly.Internal.System.IO (unsafeInlineIO)
139import qualified Streamly.Internal.Data.Array.Foreign.Mut.Type as MA
140import qualified Streamly.Internal.Data.Array.Foreign.Mut as MA
141import qualified Streamly.Internal.Data.Array.Foreign.Type as A
142import qualified Streamly.Internal.Data.Fold as FL
143import qualified Streamly.Internal.Data.Producer as Producer
144import qualified Streamly.Internal.Data.Stream.Common as P
145import qualified Streamly.Internal.Data.Stream.StreamD as D
146import qualified Streamly.Internal.Data.Unfold as Unfold
147import qualified Streamly.Internal.Data.Ring.Foreign as RB
149-------------------------------------------------------------------------------
151-------------------------------------------------------------------------------
153-- | Create an 'Array' from the first N elements of a stream. The array is
154-- allocated to size N, if the stream terminates before N elements then the
155-- array may hold less than N elements.
158{-# INLINE fromStreamN #-}
159fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
160fromStreamN n (SerialT m) = do
161 when (n < 0) $ error "writeN: negative write count specified"
162 A.fromStreamDN n $ D.fromStreamK m
164-- | Create an 'Array' from a stream. This is useful when we want to create a
165-- single array from a stream of unknown size. 'writeN' is at least twice
166-- as efficient when the size is already known.
168-- Note that if the input stream is too large memory allocation for the array
169-- may fail. When the stream size is not known, `arraysOf` followed by
170-- processing of indvidual arrays in the resulting stream should be preferred.
173{-# INLINE fromStream #-}
174fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
175fromStream (SerialT m) = P.fold A.write m
176-- write m = A.fromStreamD $ D.fromStreamK m
178-------------------------------------------------------------------------------
180-------------------------------------------------------------------------------
182{-# INLINE_NORMAL producer #-}
183producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
184producer = Producer step inject extract
187 {-# INLINE inject #-}
188 inject (Array contents start end) = return $ ReadUState contents end start
190 {-# INLINE_LATE step #-}
191 step (ReadUState contents end cur)
192 | assert (cur <= end) (cur == end) =
193 let x = unsafeInlineIO $ touch contents
194 in x `seq` return D.Stop
195 step (ReadUState contents end cur) = do
196 -- unsafeInlineIO allows us to run this in Identity monad for pure
197 -- toList/foldr case which makes them much faster due to not
198 -- accumulating the list and fusing better with the pure consumers.
200 -- This should be safe as the array contents are guaranteed to be
201 -- evaluated/written to before we peek at them.
202 let !x = unsafeInlineIO $ peek cur
203 return $ D.Yield x (ReadUState contents end (PTR_NEXT(cur,a)))
205 extract (ReadUState contents end cur) = return $ Array contents cur end
207-- | Unfold an array into a stream.
209-- /Since 0.7.0 (Streamly.Memory.Array)/
212{-# INLINE_NORMAL read #-}
213read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
214read = Producer.simplify producer
216-- | Unfold an array into a stream, does not check the end of the array, the
217-- user is responsible for terminating the stream within the array bounds. For
218-- high performance application where the end condition can be determined by
219-- a terminating fold.
221-- Written in the hope that it may be faster than "read", however, in the case
222-- for which this was written, "read" proves to be faster even though the core
223-- generated with unsafeRead looks simpler.
227{-# INLINE_NORMAL unsafeRead #-}
228unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
229unsafeRead = Unfold step inject
232 inject (Array contents start end) =
233 return (ReadUState contents end start)
235 {-# INLINE_LATE step #-}
236 step (ReadUState contents end p) = do
237 -- unsafeInlineIO allows us to run this in Identity monad for pure
238 -- toList/foldr case which makes them much faster due to not
239 -- accumulating the list and fusing better with the pure consumers.
241 -- This should be safe as the array contents are guaranteed to be
242 -- evaluated/written to before we peek at them.
243 let !x = unsafeInlineIO $ do
247 let !p1 = PTR_NEXT(p,a)
248 return $ D.Yield x (ReadUState contents end p1)
252-- >>> import qualified Streamly.Internal.Data.Array.Foreign.Type as Array
253-- >>> null arr = Array.byteLength arr == 0
257null :: Array a -> Bool
258null arr = A.byteLength arr == 0
260-- | Like 'getIndex' but indexes the array in reverse from the end.
263{-# INLINE getIndexRev #-}
264getIndexRev :: forall a. Storable a => Int -> Array a -> Maybe a
269 let elemPtr = PTR_RINDEX(aEnd arr,i,a)
270 if i >= 0 && elemPtr >= ptr
271 then Just <$> peek elemPtr
276-- >>> import qualified Streamly.Internal.Data.Array.Foreign as Array
277-- >>> last arr = Array.getIndexRev arr 0
281last :: Storable a => Array a -> Maybe a
284-------------------------------------------------------------------------------
285-- Folds with Array as the container
286-------------------------------------------------------------------------------
288-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
289-- stream to an 'Array'.
292{-# INLINE writeLastN #-}
293writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
295 | n <= 0 = fmap (const mempty) FL.drain
296 | otherwise = A.unsafeFreeze <$> Fold step initial done
300 step (Tuple3Fused' rb rh i) a = do
301 rh1 <- liftIO $ RB.unsafeInsert rb rh a
302 return $ FL.Partial $ Tuple3Fused' rb rh1 (i + 1)
305 let f (a, b) = FL.Partial $ Tuple3Fused' a b (0 :: Int)
306 in fmap f $ liftIO $ RB.new n
308 done (Tuple3Fused' rb rh i) = do
309 arr <- liftIO $ MA.newArray n
310 foldFunc i rh snoc' arr rb
312 -- XXX We should write a read unfold for ring.
313 snoc' b a = liftIO $ MA.snocUnsafe b a
316 | i < n = RB.unsafeFoldRingM
317 | otherwise = RB.unsafeFoldRingFullM
319-------------------------------------------------------------------------------
321-------------------------------------------------------------------------------
323-------------------------------------------------------------------------------
325-------------------------------------------------------------------------------
327-- | Given a sorted array, perform a binary search to find the given element.
328-- Returns the index of the element if found.
331{-# INLINE binarySearch #-}
332binarySearch :: a -> Array a -> Maybe Int
333binarySearch = undefined
335-- find/findIndex etc can potentially be implemented more efficiently on arrays
336-- compared to streams by using SIMD instructions.
337-- We can also return a bit array instead.
339-- | Perform a linear search to find all the indices where a given element is
340-- present in an array.
343findIndicesOf :: (a -> Bool) -> Unfold Identity (Array a) Int
344findIndicesOf = undefined
347findIndexOf :: (a -> Bool) -> Array a -> Maybe Int
348findIndexOf p = Unfold.fold Fold.head . Stream.unfold (findIndicesOf p)
350find :: (a -> Bool) -> Array a -> Bool
351find = Unfold.fold Fold.null . Stream.unfold (findIndicesOf p)
354-------------------------------------------------------------------------------
356-------------------------------------------------------------------------------
358-- XXX We can potentially use SIMD instructions on arrays to fold faster.
360-------------------------------------------------------------------------------
362-------------------------------------------------------------------------------
364-- | /O(1)/ Slice an array in constant time.
366-- Caution: The bounds of the slice are not checked.
371{-# INLINE getSliceUnsafe #-}
374 => Int -- ^ starting index
375 -> Int -- ^ length of the slice
378getSliceUnsafe index len (Array contents start e) =
379 let size = SIZE_OF(a)
380 fp1 = start `plusPtr` (index * size)
381 end = fp1 `plusPtr` (len * size)
382 in assert (end <= e) (Array contents fp1 end)
384-- | Split the array into a stream of slices using a predicate. The element
385-- matching the predicate is dropped.
388{-# INLINE splitOn #-}
389splitOn :: (Monad m, Storable a) =>
390 (a -> Bool) -> Array a -> SerialT m (Array a)
391splitOn predicate arr =
392 SerialT $ D.toStreamK
393 $ fmap (\(i, len) -> getSliceUnsafe i len arr)
394 $ D.sliceOnSuffix predicate (A.toStreamD arr)
396{-# INLINE genSlicesFromLen #-}
397genSlicesFromLen :: forall m a. (Monad m, Storable a)
398 => Int -- ^ from index
399 -> Int -- ^ length of the slice
400 -> Unfold m (Array a) (Int, Int)
401genSlicesFromLen from len =
402 Unfold.lmap A.unsafeThaw (MA.genSlicesFromLen from len)
404-- | Generate a stream of slices of specified length from an array, starting
405-- from the supplied array index. The last slice may be shorter than the
409{-# INLINE getSlicesFromLen #-}
410getSlicesFromLen :: forall m a. (Monad m, Storable a)
411 => Int -- ^ from index
412 -> Int -- ^ length of the slice
413 -> Unfold m (Array a) (Array a)
414getSlicesFromLen from len =
416 $ Unfold.lmap A.unsafeThaw (MA.getSlicesFromLen from len)
418-------------------------------------------------------------------------------
419-- Random reads and writes
420-------------------------------------------------------------------------------
422-- XXX Change this to a partial function instead of a Maybe type? And use
423-- MA.getIndex instead.
425-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
428{-# INLINE getIndex #-}
429getIndex :: forall a. Storable a => Int -> Array a -> Maybe a
434 let elemPtr = PTR_INDEX(ptr,i,a)
435 if i >= 0 && PTR_VALID(elemPtr,aEnd arr,a)
436 then Just <$> peek elemPtr
439-- | Given a stream of array indices, read the elements on those indices from
440-- the supplied Array. An exception is thrown if an index is out of bounds.
442-- This is the most general operation. We can implement other operations in
447-- let u = lmap (\arr -> (0, length arr - 1)) Unfold.enumerateFromTo
448-- in Unfold.lmap f (getIndices arr)
451-- let i = length arr - 1
452-- in Unfold.lmap f (getIndicesFromThenTo i (i - 1) 0)
456{-# INLINE getIndices #-}
457getIndices :: (Monad m, Storable a) => SerialT m Int -> Unfold m (Array a) a
458getIndices (SerialT stream) =
459 let unf = MA.getIndicesD (return . unsafeInlineIO) $ D.fromStreamK stream
460 in Unfold.lmap A.unsafeThaw unf
462-- | Unfolds @(from, then, to, array)@ generating a finite stream whose first
463-- element is the array value from the index @from@ and the successive elements
464-- are from the indices in increments of @then@ up to @to@. Index enumeration
465-- can occur downwards or upwards depending on whether @then@ comes before or
469-- getIndicesFromThenTo =
470-- let f (from, next, to, arr) =
471-- (Stream.enumerateFromThenTo from next to, arr)
472-- in Unfold.lmap f getIndices
476{-# INLINE getIndicesFromThenTo #-}
477getIndicesFromThenTo :: Unfold m (Int, Int, Int, Array a) a
478getIndicesFromThenTo = undefined
480-------------------------------------------------------------------------------
481-- Transform via stream operations
482-------------------------------------------------------------------------------
484-- for non-length changing operations we can use the original length for
485-- allocation. If we can predict the length then we can use the prediction for
486-- new allocation. Otherwise we can use a hint and adjust dynamically.
489-- | Transform an array into another array using a pipe transformation
493{-# INLINE runPipe #-}
494runPipe :: (MonadIO m, Storable a, Storable b)
495 => Pipe m a b -> Array a -> m (Array b)
496runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
499-- XXX For transformations that cannot change the number of elements e.g. "map"
500-- we can use a predetermined array length.
502-- | Transform an array into another array using a stream transformation
506{-# INLINE streamTransform #-}
507streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
508 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
509streamTransform f arr =
510 P.fold (A.writeWith (length arr)) $ getSerialT $ f (A.toStream arr)
512-------------------------------------------------------------------------------
514-------------------------------------------------------------------------------
516-- | Cast an array having elements of type @a@ into an array having elements of
517-- type @b@. The array size must be a multiple of the size of type @b@
518-- otherwise accessing the last element of the array may result into a crash or
528castUnsafe (Array contents start end) =
529 Array contents (castPtr start) (castPtr end)
531-- | Cast an @Array a@ into an @Array Word8@.
535asBytes :: Array a -> Array Word8
538-- | Cast an array having elements of type @a@ into an array having elements of
539-- type @b@. The length of the array should be a multiple of the size of the
540-- target element otherwise 'Nothing' is returned.
544cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
546 let len = A.byteLength arr
547 r = len `mod` SIZE_OF(b)
550 else Just $ castUnsafe arr
552-- | Convert an array of any type into a null terminated CString Ptr.
556-- /O(n) Time: (creates a copy of the array)/
560asCStringUnsafe :: Array a -> (CString -> IO b) -> IO b
561asCStringUnsafe arr act = do
562 let arr1 = asBytes arr <> A.fromList [0]
563 asPtrUnsafe arr1 $ \ptr -> act (castPtr ptr)
565-------------------------------------------------------------------------------
567-------------------------------------------------------------------------------
569-- | Fold an array using a 'Fold'.
573fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
574fold f arr = P.fold f (getSerialT (A.toStream arr))
576-- | Fold an array using a stream fold operation.
579{-# INLINE streamFold #-}
580streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
581streamFold 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