on 9119e44 help sign in
585 lines 19 kB history raw
1{-# LANGUAGE UnboxedTuples #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Internal.Data.Array.Foreign
7-- Copyright : (c) 2019 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
14-- To summarize:
15--
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
20--
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
26-- arrays at once.
27--
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
33-- pressure to GC.
35module Streamly.Internal.Data.Array.Foreign
36 (
37 Array
39 -- * Construction
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.
44 , A.fromPtr
45 , A.fromAddr#
46 , A.fromCString#
48 -- Pure List APIs
49 , A.fromListN
50 , A.fromList
52 -- Stream Folds
53 , fromStreamN
54 , fromStream
56 -- Monadic Folds
57 , A.writeN -- drop new
58 , A.writeNAligned
59 , A.write -- full buffer
60 , writeLastN
62 -- * Elimination
63 , A.toList
64 , A.toStream
65 , A.toStreamRev
66 , read
67 , unsafeRead -- XXX readUnsafe?
68 , A.readRev
69 , producer -- experimental
71 -- * Random Access
72 -- , (!!)
73 , getIndex
74 , A.unsafeIndex -- XXX Rename to getIndexUnsafe??
75 , getIndexRev
76 , last -- XXX getIndexLast?
77 , getIndices
78 , getIndicesFromThenTo
79 -- , getIndicesFrom -- read from a given position to the end of file
80 -- , getIndicesUpto -- read from beginning up to the given position
81 -- , getIndicesFromTo
82 -- , getIndicesFromRev -- read from a given position to the beginning of file
83 -- , getIndicesUptoRev -- read from end to the given position in file
85 -- * Size
86 , length
87 , null
89 -- * Search
90 , binarySearch
91 , findIndicesOf
92 -- , findIndexOf
93 -- , find
95 -- * Casting
96 , cast
97 , asBytes
98 , unsafeCast -- castUnsafe?
99 , unsafeAsPtr -- asPtrUnsafe?
100 , unsafeAsCString -- asCStringUnsafe?
101 , A.unsafeFreeze -- asImmutableUnsafe?
102 , A.unsafeThaw -- asMutableUnsafe?
104 -- * Subarrays
105 , getSliceUnsafe
106 -- , getSlice
107 , genSlicesFromLen
108 , getSlicesFromLen
109 , splitOn
111 -- * Streaming Operations
112 , streamTransform
114 -- ** Folding
115 , streamFold
116 , fold
117 )
118where
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 ((<>))
126#endif
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)
161#else
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
166#endif
168-------------------------------------------------------------------------------
169-- Construction
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.
175--
176-- /Pre-release/
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.
186--
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.
190--
191-- /Pre-release/
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-------------------------------------------------------------------------------
198-- Elimination
199-------------------------------------------------------------------------------
201-- | Unfold an array into a stream.
202--
203-- /Since 0.7.0 (Streamly.Memory.Array)/
204--
205-- @since 0.8.0
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.
218--
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.
222--
223-- /Pre-release/
224--
225{-# INLINE_NORMAL unsafeRead #-}
226unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
227unsafeRead = Unfold step inject
228 where
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.
237 --
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
241 r <- peek (Ptr p)
242 touch contents
243 return r
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', () #)
249-- |
250--
251-- >>> import qualified Streamly.Internal.Data.Array.Foreign.Type as Array
252-- >>> null arr = Array.byteLength arr == 0
253--
254-- /Pre-release/
255{-# INLINE null #-}
256null :: Array a -> Bool
257null arr = A.byteLength arr == 0
259-- | Like 'getIndex' but indexes the array in reverse from the end.
260--
261-- /Pre-release/
262{-# INLINE getIndexRev #-}
263getIndexRev :: forall a. Storable a => Array a -> Int -> Maybe a
264getIndexRev arr i =
265 unsafeInlineIO $
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
271 else return Nothing
273-- |
274--
275-- >>> import qualified Streamly.Internal.Data.Array.Foreign as Array
276-- >>> last arr = Array.getIndexRev arr 0
277--
278-- /Pre-release/
279{-# INLINE last #-}
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'.
289--
290-- @since 0.8.0
291{-# INLINE writeLastN #-}
292writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
293writeLastN n
294 | n <= 0 = fmap (const mempty) FL.drain
295 | otherwise = A.unsafeFreeze <$> Fold step initial done
297 where
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)
303 initial =
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
314 foldFunc i
315 | i < n = RB.unsafeFoldRingM
316 | otherwise = RB.unsafeFoldRingFullM
318-------------------------------------------------------------------------------
319-- Random Access
320-------------------------------------------------------------------------------
322-------------------------------------------------------------------------------
323-- Searching
324-------------------------------------------------------------------------------
326-- | Given a sorted array, perform a binary search to find the given element.
327-- Returns the index of the element if found.
328--
329-- /Unimplemented/
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.
340--
341-- /Unimplemented/
342findIndicesOf :: (a -> Bool) -> Unfold Identity (Array a) Int
343findIndicesOf = undefined
345{-
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)
351-}
353-------------------------------------------------------------------------------
354-- Folds
355-------------------------------------------------------------------------------
357-- XXX We can potentially use SIMD instructions on arrays to fold faster.
359-------------------------------------------------------------------------------
360-- Slice
361-------------------------------------------------------------------------------
363-- | /O(1)/ Slice an array in constant time.
364--
365-- Caution: The bounds of the slice are not checked.
366--
367-- /Unsafe/
368--
369-- /Pre-release/
370{-# INLINE getSliceUnsafe #-}
371getSliceUnsafe ::
372 forall a. Storable a
373 => Int -- ^ starting index
374 -> Int -- ^ length of the slice
375 -> Array a
376 -> Array a
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.
385--
386-- /Pre-release/
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
403-- requested length.
404--
405-- /Pre-release//
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 =
412 fmap A.unsafeFreeze
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.
421--
422-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
423--
424-- @since 0.8.0
425{-# INLINE getIndex #-}
426getIndex :: forall a. Storable a => Array a -> Int -> Maybe a
427getIndex arr i =
428 unsafeInlineIO $
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
434 else return Nothing
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.
438--
439-- This is the most general operation. We can implement other operations in
440-- terms of this:
441--
442-- @
443-- read =
444-- let u = lmap (\arr -> (0, length arr - 1)) Unfold.enumerateFromTo
445-- in Unfold.lmap f (getIndices arr)
446--
447-- readRev =
448-- let i = length arr - 1
449-- in Unfold.lmap f (getIndicesFromThenTo i (i - 1) 0)
450-- @
451--
452-- /Unimplemented/
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
461-- after @from@.
462--
463-- @
464-- getIndicesFromThenTo =
465-- let f (from, next, to, arr) =
466-- (Stream.enumerateFromThenTo from next to, arr)
467-- in Unfold.lmap f getIndices
468-- @
469--
470-- /Unimplemented/
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.
483{-
484-- | Transform an array into another array using a pipe transformation
485-- operation.
486--
487-- @since 0.7.0
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)
492-}
494-- XXX For transformations that cannot change the number of elements e.g. "map"
495-- we can use a predetermined array length.
496--
497-- | Transform an array into another array using a stream transformation
498-- operation.
499--
500-- /Pre-release/
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-------------------------------------------------------------------------------
508-- Casts
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
514-- a random value.
515--
516-- /Pre-release/
517--
518unsafeCast ::
519#ifdef DEVBUILD
520 Storable b =>
521#endif
522 Array a -> Array b
523unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
525-- | Cast an @Array a@ into an @Array Word8@.
526--
527-- @since 0.8.0
528--
529asBytes :: Array a -> Array Word8
530asBytes = unsafeCast
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.
535--
536-- @since 0.8.0
537--
538cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
539cast arr =
540 let len = A.byteLength arr
541 r = len `mod` sizeOf (undefined :: b)
542 in if r /= 0
543 then Nothing
544 else Just $ unsafeCast arr
546-- | Use an @Array a@ as @Ptr b@.
547--
548-- /Unsafe/
549--
550-- /Pre-release/
551--
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.
557--
558-- /Unsafe/
559--
560-- /O(n) Time: (creates a copy of the array)/
561--
562-- /Pre-release/
563--
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-------------------------------------------------------------------------------
570-- Folds
571-------------------------------------------------------------------------------
573-- | Fold an array using a 'Fold'.
574--
575-- /Pre-release/
576{-# INLINE 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.
581--
582-- /Pre-release/
583{-# INLINE streamFold #-}
584streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
585streamFold f arr = f (A.toStream arr)