on ce93caa help sign in
594 lines 20 kB history raw
1-- |
2-- Module : Streamly.Internal.Data.Array.Foreign
3-- Copyright : (c) 2019 Composewell Technologies
4--
5-- License : BSD3
6-- Maintainer : streamly@composewell.com
7-- Stability : experimental
8-- Portability : GHC
9--
10-- To summarize:
11--
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
16--
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
22-- arrays at once.
23--
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
29-- pressure to GC.
31module Streamly.Internal.Data.Array.Foreign
32 (
33 Array
35 -- * Construction
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.
40 , A.fromPtr
41 , A.fromAddr#
42 , A.fromCString#
44 -- Pure List APIs
45 , A.fromListN
46 , A.fromList
48 -- Stream Folds
49 , fromStreamN
50 , fromStream
52 -- Monadic Folds
53 , A.writeN -- drop new
54 , A.writeNAligned
55 , A.write -- full buffer
56 , writeLastN
58 -- * Elimination
59 , A.toList
60 , A.toStream
61 , A.toStreamRev
62 , read
63 , unsafeRead -- XXX readUnsafe?
64 , A.readRev
65 , producer -- experimental
67 -- * Random Access
68 -- , (!!)
69 , getIndex
70 , A.unsafeIndex -- XXX Rename to getIndexUnsafe??
71 , getIndexRev
72 , last -- XXX getIndexLast?
73 , getIndices
74 , getIndicesFromThenTo
75 -- , getIndicesFrom -- read from a given position to the end of file
76 -- , getIndicesUpto -- read from beginning up to the given position
77 -- , getIndicesFromTo
78 -- , getIndicesFromRev -- read from a given position to the beginning of file
79 -- , getIndicesUptoRev -- read from end to the given position in file
81 -- * Size
82 , length
83 , null
85 -- * Search
86 , binarySearch
87 , findIndicesOf
88 -- , findIndexOf
89 -- , find
91 -- * Casting
92 , cast
93 , asBytes
94 , unsafeCast -- castUnsafe?
95 , unsafeAsPtr -- asPtrUnsafe?
96 , unsafeAsCString -- asCStringUnsafe?
97 , A.unsafeFreeze -- asImmutableUnsafe?
98 , A.unsafeThaw -- asMutableUnsafe?
100 -- * Subarrays
101 , getSliceUnsafe
102 -- , getSlice
103 , genSlicesFromLen
104 , getSlicesFromLen
105 , splitOn
107 -- * Streaming Operations
108 , streamTransform
110 -- ** Folding
111 , streamFold
112 , fold
113 )
114where
116#include "inline.hs"
117#include "ArrayMacros.h"
119import Control.Exception (assert)
120import Control.Monad (when)
121import Control.Monad.IO.Class (MonadIO(..))
122import Data.Functor.Identity (Identity)
123#if !(MIN_VERSION_base(4,11,0))
124import Data.Semigroup ((<>))
125#endif
126import Data.Word (Word8)
127import Foreign.C.String (CString)
128import Foreign.Ptr (plusPtr, castPtr)
129import Foreign.Storable (Storable(..))
130import Prelude hiding (length, null, last, map, (!!), read, concat)
132import GHC.Ptr (Ptr(..))
134import Streamly.Internal.Data.Array.Foreign.Mut.Type (ReadUState(..), touch)
135import Streamly.Internal.Data.Array.Foreign.Type (Array(..), length)
136import Streamly.Internal.Data.Fold.Type (Fold(..))
137import Streamly.Internal.Data.Producer.Type (Producer(..))
138import Streamly.Internal.Data.Stream.Serial (SerialT(..))
139import Streamly.Internal.Data.Tuple.Strict (Tuple3'(..))
140import Streamly.Internal.Data.Unfold.Type (Unfold(..))
141import Streamly.Internal.System.IO (unsafeInlineIO)
143import qualified Streamly.Internal.Data.Array.Foreign.Mut.Type as MA
144import qualified Streamly.Internal.Data.Array.Foreign.Mut as MA
145import qualified Streamly.Internal.Data.Array.Foreign.Type as A
146import qualified Streamly.Internal.Data.Fold as FL
147import qualified Streamly.Internal.Data.Producer as Producer
148import qualified Streamly.Internal.Data.Stream.IsStream.Type as IsStream
149import qualified Streamly.Internal.Data.Stream.Prelude as P
150import qualified Streamly.Internal.Data.Stream.StreamD as D
151import qualified Streamly.Internal.Data.Unfold as Unfold
152import qualified Streamly.Internal.Data.Ring.Foreign as RB
154-------------------------------------------------------------------------------
155-- Construction
156-------------------------------------------------------------------------------
158-- | Create an 'Array' from the first N elements of a stream. The array is
159-- allocated to size N, if the stream terminates before N elements then the
160-- array may hold less than N elements.
161--
162-- /Pre-release/
163{-# INLINE fromStreamN #-}
164fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
165fromStreamN n (SerialT m) = do
166 when (n < 0) $ error "writeN: negative write count specified"
167 A.fromStreamDN n $ D.fromStreamK m
169-- | Create an 'Array' from a stream. This is useful when we want to create a
170-- single array from a stream of unknown size. 'writeN' is at least twice
171-- as efficient when the size is already known.
172--
173-- Note that if the input stream is too large memory allocation for the array
174-- may fail. When the stream size is not known, `arraysOf` followed by
175-- processing of indvidual arrays in the resulting stream should be preferred.
176--
177-- /Pre-release/
178{-# INLINE fromStream #-}
179fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
180fromStream (SerialT m) = P.fold A.write m
181-- write m = A.fromStreamD $ D.fromStreamK m
183-------------------------------------------------------------------------------
184-- Elimination
185-------------------------------------------------------------------------------
187{-# INLINE_NORMAL producer #-}
188producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
189producer = Producer step inject extract
190 where
192 {-# INLINE inject #-}
193 inject (Array contents start end) = return $ ReadUState contents end start
195 {-# INLINE_LATE step #-}
196 step (ReadUState contents end cur)
197 | assert (cur <= end) (cur == end) =
198 let x = unsafeInlineIO $ touch contents
199 in x `seq` return D.Stop
200 step (ReadUState contents end cur) = do
201 -- unsafeInlineIO allows us to run this in Identity monad for pure
202 -- toList/foldr case which makes them much faster due to not
203 -- accumulating the list and fusing better with the pure consumers.
204 --
205 -- This should be safe as the array contents are guaranteed to be
206 -- evaluated/written to before we peek at them.
207 let !x = unsafeInlineIO $ peek cur
208 return $ D.Yield x (ReadUState contents end (PTR_NEXT(cur,a)))
210 extract (ReadUState contents end cur) = return $ Array contents cur end
212-- | Unfold an array into a stream.
213--
214-- /Since 0.7.0 (Streamly.Memory.Array)/
215--
216-- @since 0.8.0
217{-# INLINE_NORMAL read #-}
218read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
219read = Producer.simplify producer
221-- | Unfold an array into a stream, does not check the end of the array, the
222-- user is responsible for terminating the stream within the array bounds. For
223-- high performance application where the end condition can be determined by
224-- a terminating fold.
225--
226-- Written in the hope that it may be faster than "read", however, in the case
227-- for which this was written, "read" proves to be faster even though the core
228-- generated with unsafeRead looks simpler.
229--
230-- /Pre-release/
231--
232{-# INLINE_NORMAL unsafeRead #-}
233unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
234unsafeRead = Unfold step inject
235 where
237 inject (Array contents start end) =
238 return (ReadUState contents end start)
240 {-# INLINE_LATE step #-}
241 step (ReadUState contents end p) = 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.
245 --
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 = unsafeInlineIO $ do
249 r <- peek p
250 touch contents
251 return r
252 let !p1 = PTR_NEXT(p,a)
253 return $ D.Yield x (ReadUState contents end p1)
255-- |
256--
257-- >>> import qualified Streamly.Internal.Data.Array.Foreign.Type as Array
258-- >>> null arr = Array.byteLength arr == 0
259--
260-- /Pre-release/
261{-# INLINE null #-}
262null :: Array a -> Bool
263null arr = A.byteLength arr == 0
265-- | Like 'getIndex' but indexes the array in reverse from the end.
266--
267-- /Pre-release/
268{-# INLINE getIndexRev #-}
269getIndexRev :: forall a. Storable a => Array a -> Int -> Maybe a
270getIndexRev arr i =
271 unsafeInlineIO
272 $ MA.unsafeWithArrayContents (arrContents arr) (arrStart arr)
273 $ \ptr -> do
274 let elemPtr = PTR_RINDEX(aEnd arr,i,a)
275 if i >= 0 && elemPtr >= ptr
276 then Just <$> peek elemPtr
277 else return Nothing
279-- |
280--
281-- >>> import qualified Streamly.Internal.Data.Array.Foreign as Array
282-- >>> last arr = Array.getIndexRev arr 0
283--
284-- /Pre-release/
285{-# INLINE last #-}
286last :: Storable a => Array a -> Maybe a
287last arr = getIndexRev arr 0
289-------------------------------------------------------------------------------
290-- Folds with Array as the container
291-------------------------------------------------------------------------------
293-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
294-- stream to an 'Array'.
295--
296-- @since 0.8.0
297{-# INLINE writeLastN #-}
298writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
299writeLastN n
300 | n <= 0 = fmap (const mempty) FL.drain
301 | otherwise = A.unsafeFreeze <$> Fold step initial done
303 where
305 step (Tuple3' rb rh i) a = do
306 rh1 <- liftIO $ RB.unsafeInsert rb rh a
307 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
309 initial =
310 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
311 in fmap f $ liftIO $ RB.new n
313 done (Tuple3' rb rh i) = do
314 arr <- liftIO $ MA.newArray n
315 foldFunc i rh snoc' arr rb
317 -- XXX We should write a read unfold for ring.
318 snoc' b a = liftIO $ MA.snocUnsafe b a
320 foldFunc i
321 | i < n = RB.unsafeFoldRingM
322 | otherwise = RB.unsafeFoldRingFullM
324-------------------------------------------------------------------------------
325-- Random Access
326-------------------------------------------------------------------------------
328-------------------------------------------------------------------------------
329-- Searching
330-------------------------------------------------------------------------------
332-- | Given a sorted array, perform a binary search to find the given element.
333-- Returns the index of the element if found.
334--
335-- /Unimplemented/
336{-# INLINE binarySearch #-}
337binarySearch :: a -> Array a -> Maybe Int
338binarySearch = undefined
340-- find/findIndex etc can potentially be implemented more efficiently on arrays
341-- compared to streams by using SIMD instructions.
342-- We can also return a bit array instead.
344-- | Perform a linear search to find all the indices where a given element is
345-- present in an array.
346--
347-- /Unimplemented/
348findIndicesOf :: (a -> Bool) -> Unfold Identity (Array a) Int
349findIndicesOf = undefined
351{-
352findIndexOf :: (a -> Bool) -> Array a -> Maybe Int
353findIndexOf p = Unfold.fold Fold.head . Stream.unfold (findIndicesOf p)
355find :: (a -> Bool) -> Array a -> Bool
356find = Unfold.fold Fold.null . Stream.unfold (findIndicesOf p)
357-}
359-------------------------------------------------------------------------------
360-- Folds
361-------------------------------------------------------------------------------
363-- XXX We can potentially use SIMD instructions on arrays to fold faster.
365-------------------------------------------------------------------------------
366-- Slice
367-------------------------------------------------------------------------------
369-- | /O(1)/ Slice an array in constant time.
370--
371-- Caution: The bounds of the slice are not checked.
372--
373-- /Unsafe/
374--
375-- /Pre-release/
376{-# INLINE getSliceUnsafe #-}
377getSliceUnsafe ::
378 forall a. Storable a
379 => Int -- ^ starting index
380 -> Int -- ^ length of the slice
381 -> Array a
382 -> Array a
383getSliceUnsafe index len (Array contents start e) =
384 let size = SIZE_OF(a)
385 fp1 = start `plusPtr` (index * size)
386 end = fp1 `plusPtr` (len * size)
387 in assert (end <= e) (Array contents fp1 end)
389-- | Split the array into a stream of slices using a predicate. The element
390-- matching the predicate is dropped.
391--
392-- /Pre-release/
393{-# INLINE splitOn #-}
394splitOn :: (Monad m, Storable a) =>
395 (a -> Bool) -> Array a -> SerialT m (Array a)
396splitOn predicate arr =
397 IsStream.fromStreamD
398 $ fmap (\(i, len) -> getSliceUnsafe i len arr)
399 $ D.sliceOnSuffix predicate (A.toStreamD arr)
401{-# INLINE genSlicesFromLen #-}
402genSlicesFromLen :: forall m a. (Monad m, Storable a)
403 => Int -- ^ from index
404 -> Int -- ^ length of the slice
405 -> Unfold m (Array a) (Int, Int)
406genSlicesFromLen from len =
407 Unfold.lmap A.unsafeThaw (MA.genSlicesFromLen from len)
409-- | Generate a stream of slices of specified length from an array, starting
410-- from the supplied array index. The last slice may be shorter than the
411-- requested length.
412--
413-- /Pre-release//
414{-# INLINE getSlicesFromLen #-}
415getSlicesFromLen :: forall m a. (Monad m, Storable a)
416 => Int -- ^ from index
417 -> Int -- ^ length of the slice
418 -> Unfold m (Array a) (Array a)
419getSlicesFromLen from len =
420 fmap A.unsafeFreeze
421 $ Unfold.lmap A.unsafeThaw (MA.getSlicesFromLen from len)
423-------------------------------------------------------------------------------
424-- Random reads and writes
425-------------------------------------------------------------------------------
427-- XXX Change this to a partial function instead of a Maybe type? And use
428-- MA.getIndex instead.
429--
430-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
431--
432-- @since 0.8.0
433{-# INLINE getIndex #-}
434getIndex :: forall a. Storable a => Array a -> Int -> Maybe a
435getIndex arr i =
436 unsafeInlineIO
437 $ MA.unsafeWithArrayContents (arrContents arr) (arrStart arr)
438 $ \ptr -> do
439 let elemPtr = PTR_INDEX(ptr,i,a)
440 if i >= 0 && PTR_VALID(elemPtr,aEnd arr,a)
441 then Just <$> peek elemPtr
442 else return Nothing
444-- | Given a stream of array indices, read the elements on those indices from
445-- the supplied Array. An exception is thrown if an index is out of bounds.
446--
447-- This is the most general operation. We can implement other operations in
448-- terms of this:
449--
450-- @
451-- read =
452-- let u = lmap (\arr -> (0, length arr - 1)) Unfold.enumerateFromTo
453-- in Unfold.lmap f (getIndices arr)
454--
455-- readRev =
456-- let i = length arr - 1
457-- in Unfold.lmap f (getIndicesFromThenTo i (i - 1) 0)
458-- @
459--
460-- /Unimplemented/
461{-# INLINE getIndices #-}
462getIndices :: Unfold m (Array a) Int -> Unfold m (Array a) a
463getIndices = undefined
465-- | Unfolds @(from, then, to, array)@ generating a finite stream whose first
466-- element is the array value from the index @from@ and the successive elements
467-- are from the indices in increments of @then@ up to @to@. Index enumeration
468-- can occur downwards or upwards depending on whether @then@ comes before or
469-- after @from@.
470--
471-- @
472-- getIndicesFromThenTo =
473-- let f (from, next, to, arr) =
474-- (Stream.enumerateFromThenTo from next to, arr)
475-- in Unfold.lmap f getIndices
476-- @
477--
478-- /Unimplemented/
479{-# INLINE getIndicesFromThenTo #-}
480getIndicesFromThenTo :: Unfold m (Int, Int, Int, Array a) a
481getIndicesFromThenTo = undefined
483-------------------------------------------------------------------------------
484-- Transform via stream operations
485-------------------------------------------------------------------------------
487-- for non-length changing operations we can use the original length for
488-- allocation. If we can predict the length then we can use the prediction for
489-- new allocation. Otherwise we can use a hint and adjust dynamically.
491{-
492-- | Transform an array into another array using a pipe transformation
493-- operation.
494--
495-- @since 0.7.0
496{-# INLINE runPipe #-}
497runPipe :: (MonadIO m, Storable a, Storable b)
498 => Pipe m a b -> Array a -> m (Array b)
499runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
500-}
502-- XXX For transformations that cannot change the number of elements e.g. "map"
503-- we can use a predetermined array length.
504--
505-- | Transform an array into another array using a stream transformation
506-- operation.
507--
508-- /Pre-release/
509{-# INLINE streamTransform #-}
510streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
511 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
512streamTransform f arr =
513 P.fold (A.writeWith (length arr)) $ getSerialT $ f (A.toStream arr)
515-------------------------------------------------------------------------------
516-- Casts
517-------------------------------------------------------------------------------
519-- | Cast an array having elements of type @a@ into an array having elements of
520-- type @b@. The array size must be a multiple of the size of type @b@
521-- otherwise accessing the last element of the array may result into a crash or
522-- a random value.
523--
524-- /Pre-release/
525--
526unsafeCast ::
527#ifdef DEVBUILD
528 Storable b =>
529#endif
530 Array a -> Array b
531unsafeCast (Array contents start end) =
532 Array contents (castPtr start) (castPtr end)
534-- | Cast an @Array a@ into an @Array Word8@.
535--
536-- @since 0.8.0
537--
538asBytes :: Array a -> Array Word8
539asBytes = unsafeCast
541-- | Cast an array having elements of type @a@ into an array having elements of
542-- type @b@. The length of the array should be a multiple of the size of the
543-- target element otherwise 'Nothing' is returned.
544--
545-- @since 0.8.0
546--
547cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
548cast arr =
549 let len = A.byteLength arr
550 r = len `mod` SIZE_OF(b)
551 in if r /= 0
552 then Nothing
553 else Just $ unsafeCast arr
555-- | Use an @Array a@ as @Ptr b@.
556--
557-- /Unsafe/
558--
559-- /Pre-release/
560--
561unsafeAsPtr :: Array a -> (Ptr b -> IO c) -> IO c
562unsafeAsPtr Array{..} act = do
563 MA.unsafeWithArrayContents arrContents arrStart $ \ptr -> act (castPtr ptr)
565-- | Convert an array of any type into a null terminated CString Ptr.
566--
567-- /Unsafe/
568--
569-- /O(n) Time: (creates a copy of the array)/
570--
571-- /Pre-release/
572--
573unsafeAsCString :: Array a -> (CString -> IO b) -> IO b
574unsafeAsCString arr act = do
575 let Array{..} = asBytes arr <> A.fromList [0]
576 MA.unsafeWithArrayContents arrContents arrStart $ \ptr -> act (castPtr ptr)
578-------------------------------------------------------------------------------
579-- Folds
580-------------------------------------------------------------------------------
582-- | Fold an array using a 'Fold'.
583--
584-- /Pre-release/
585{-# INLINE fold #-}
586fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
587fold f arr = P.fold f (getSerialT (A.toStream arr))
589-- | Fold an array using a stream fold operation.
590--
591-- /Pre-release/
592{-# INLINE streamFold #-}
593streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
594streamFold f arr = f (A.toStream arr)