on 38528ff help sign in
615 lines 20 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 -- , defaultChunkSize
41 -- * Construction
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.
46 , A.fromPtr
47 , A.fromAddr#
48 , A.fromCString#
50 -- Pure List APIs
51 , A.fromListN
52 , A.fromList
54 -- Stream Folds
55 , fromStreamN
56 , fromStream
58 -- Monadic APIs
59 -- , newArray
60 , A.writeN -- drop new
61 , A.writeNAligned
62 , A.write -- full buffer
63 , writeLastN
65 -- * Elimination
67 , A.toList
68 , A.toStream
69 , A.toStreamRev
70 , read
71 , producer
72 , unsafeRead
73 , A.readRev
74 -- , readChunksOf
76 -- * Random Access
77 , length
78 , null
79 , last
80 -- , (!!)
81 , getIndex
82 , A.unsafeIndex
83 -- , readIndices
84 -- , readRanges
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
90 -- , readFromTo
91 -- , readFromThenTo
93 -- , readChunksOfFrom
94 -- , ...
96 -- , writeIndex
97 -- , writeFrom -- start writing at the given position
98 -- , writeFromRev
99 -- , writeTo -- write from beginning up to the given position
100 -- , writeToRev
101 -- , writeFromTo
102 -- , writeFromThenTo
103 --
104 -- , writeChunksOfFrom
105 -- , ...
107 , writeIndex
108 --, writeIndices
109 --, writeRanges
111 -- -- * Search
112 -- , bsearch
113 -- , bsearchIndex
114 -- , find
115 -- , findIndex
116 -- , findIndices
118 -- -- * In-pace mutation (for Mutable Array type)
119 -- , partitionBy
120 -- , shuffleBy
121 -- , foldtWith
122 -- , foldbWith
124 , unsafeSlice
126 -- * Immutable Transformations
127 , streamTransform
129 -- * Casting
130 , cast
131 , unsafeCast
132 , unsafeAsPtr
133 , asBytes
134 , unsafeAsCString
136 -- * Folding Arrays
137 , streamFold
138 , fold
139 )
140where
142import Control.Monad (when)
143import Control.Monad.IO.Class (MonadIO(..))
144#if !(MIN_VERSION_base(4,11,0))
145import Data.Semigroup ((<>))
146#endif
147import Data.Word (Word8)
148-- import Data.Functor.Identity (Identity)
149import Foreign.C.String (CString)
150import Foreign.ForeignPtr (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.BaseCompat
162import Streamly.Internal.Data.Array.Foreign.Type (Array(..), length)
163import Streamly.Internal.Data.Fold.Type (Fold(..))
164import Streamly.Internal.Data.Producer.Type (Producer)
165import Streamly.Internal.Data.Stream.Serial (SerialT)
166import Streamly.Internal.Data.Tuple.Strict (Tuple3'(..))
167import Streamly.Internal.Data.Unfold.Type (Unfold(..))
169import qualified Streamly.Internal.Data.Array.Foreign.Mut.Type as MA
170import qualified Streamly.Internal.Data.Array.Foreign.Type as A
171import qualified Streamly.Internal.Data.Fold as FL
172import qualified Streamly.Internal.Data.Stream.Prelude as P
173import qualified Streamly.Internal.Data.Stream.Serial as Serial
174import qualified Streamly.Internal.Data.Stream.StreamD as D
175import qualified Streamly.Internal.Data.Unfold as Unfold
176import qualified Streamly.Internal.Data.Producer.Type as Producer
177import qualified Streamly.Internal.Ring.Foreign as RB
179#if MIN_VERSION_base(4,10,0)
180import Foreign.ForeignPtr (plusForeignPtr)
181#else
182import GHC.Base (Int(..), plusAddr#)
183import GHC.ForeignPtr (ForeignPtr(..))
184plusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b
185plusForeignPtr (ForeignPtr addr c) (I# d) = ForeignPtr (plusAddr# addr d) c
186#endif
188-------------------------------------------------------------------------------
189-- Construction
190-------------------------------------------------------------------------------
192-- | Create an 'Array' from the first N elements of a stream. The array is
193-- allocated to size N, if the stream terminates before N elements then the
194-- array may hold less than N elements.
195--
196-- /Pre-release/
197{-# INLINE fromStreamN #-}
198fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
199fromStreamN n m = do
200 when (n < 0) $ error "writeN: negative write count specified"
201 A.fromStreamDN n $ D.toStreamD m
203-- | Create an 'Array' from a stream. This is useful when we want to create a
204-- single array from a stream of unknown size. 'writeN' is at least twice
205-- as efficient when the size is already known.
206--
207-- Note that if the input stream is too large memory allocation for the array
208-- may fail. When the stream size is not known, `arraysOf` followed by
209-- processing of indvidual arrays in the resulting stream should be preferred.
210--
211-- /Pre-release/
212{-# INLINE fromStream #-}
213fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
214fromStream = P.fold A.write
215-- write m = A.fromStreamD $ D.toStreamD m
217-------------------------------------------------------------------------------
218-- Elimination
219-------------------------------------------------------------------------------
221-- | Unfold an array into a stream.
222--
223-- /Since 0.7.0 (Streamly.Memory.Array)/
224--
225-- @since 0.8.0
226{-# INLINE_NORMAL read #-}
227read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
228read = Unfold.lmap A.unsafeThaw MA.read
230{-# INLINE_NORMAL producer #-}
231producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
232producer = Producer.translate A.unsafeThaw A.unsafeFreeze MA.producer
234-- | Unfold an array into a stream, does not check the end of the array, the
235-- user is responsible for terminating the stream within the array bounds. For
236-- high performance application where the end condition can be determined by
237-- a terminating fold.
238--
239-- Written in the hope that it may be faster than "read", however, in the case
240-- for which this was written, "read" proves to be faster even though the core
241-- generated with unsafeRead looks simpler.
242--
243-- /Pre-release/
244--
245{-# INLINE_NORMAL unsafeRead #-}
246unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
247unsafeRead = Unfold step inject
248 where
250 inject (Array fp _) = return fp
252 {-# INLINE_LATE step #-}
253 step (ForeignPtr p contents) = do
254 -- unsafeInlineIO allows us to run this in Identity monad for pure
255 -- toList/foldr case which makes them much faster due to not
256 -- accumulating the list and fusing better with the pure consumers.
257 --
258 -- This should be safe as the array contents are guaranteed to be
259 -- evaluated/written to before we peek at them.
260 let !x = A.unsafeInlineIO $ do
261 r <- peek (Ptr p)
262 touch contents
263 return r
264 let !(Ptr p1) = Ptr p `plusPtr` sizeOf (undefined :: a)
265 return $ D.Yield x (ForeignPtr p1 contents)
267 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
269-- | > null arr = length arr == 0
270--
271-- /Pre-release/
272{-# INLINE null #-}
273null :: Storable a => Array a -> Bool
274null arr = length arr == 0
276-- | > last arr = getIndex arr (length arr - 1)
277--
278-- /Pre-release/
279{-# INLINE last #-}
280last :: Storable a => Array a -> Maybe a
281last arr = getIndex arr (length arr - 1)
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 snoc' b a = liftIO $ MA.unsafeSnoc b a
313 foldFunc i
314 | i < n = RB.unsafeFoldRingM
315 | otherwise = RB.unsafeFoldRingFullM
317-------------------------------------------------------------------------------
318-- Random Access
319-------------------------------------------------------------------------------
321-------------------------------------------------------------------------------
322-- Searching
323-------------------------------------------------------------------------------
325{-
326-- | Perform a binary search in the array to find an element.
327bsearch :: a -> Array a -> Maybe Bool
328bsearch = undefined
330-- | Perform a binary search in the array to find an element index.
331{-# INLINE elemIndex #-}
332bsearchIndex :: a -> Array a -> Maybe Int
333bsearchIndex elem arr = undefined
335-- find/findIndex etc can potentially be implemented more efficiently on arrays
336-- compared to streams by using SIMD instructions.
338find :: (a -> Bool) -> Array a -> Bool
339find = undefined
341findIndex :: (a -> Bool) -> Array a -> Maybe Int
342findIndex = undefined
344findIndices :: (a -> Bool) -> Array a -> Array Int
345findIndices = undefined
346-}
348-------------------------------------------------------------------------------
349-- Folds
350-------------------------------------------------------------------------------
352-- XXX We can potentially use SIMD instructions on arrays to fold faster.
354-------------------------------------------------------------------------------
355-- Slice and splice
356-------------------------------------------------------------------------------
358-- | /O(1)/ Slice an array in constant time.
359--
360-- Caution: The bounds of the slice are not checked.
361--
362-- /Unsafe/
363--
364-- /Pre-release/
365{-# INLINE unsafeSlice #-}
366unsafeSlice ::
367 forall a. Storable a
368 => Int -- ^ starting index
369 -> Int -- ^ length of the slice
370 -> Array a
371 -> Array a
372unsafeSlice start len (Array fp _) =
373 let size = sizeOf (undefined :: a)
374 fp1 = fp `plusForeignPtr` (start * size)
375 end = unsafeForeignPtrToPtr fp1 `plusPtr` (len * size)
376 in Array fp1 end
378{-
380splitAt :: Int -> Array a -> (Array a, Array a)
381splitAt i arr = undefined
383-- XXX This operation can be performed efficiently via streams.
384-- | Append two arrays together to create a single array.
385splice :: Array a -> Array a -> Array a
386splice arr1 arr2 = undefined
388-------------------------------------------------------------------------------
389-- In-place mutation APIs
390-------------------------------------------------------------------------------
392-- | Partition an array into two halves using a partitioning predicate. The
393-- first half retains values where the predicate is 'False' and the second half
394-- retains values where the predicate is 'True'.
395{-# INLINE partitionBy #-}
396partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
397partitionBy f arr = undefined
399-- | Shuffle corresponding elements from two arrays using a shuffle function.
400-- If the shuffle function returns 'False' then do nothing otherwise swap the
401-- elements. This can be used in a bottom up fold to shuffle or reorder the
402-- elements.
403shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
404shuffleBy f arr1 arr2 = undefined
406-- XXX we can also make the folds partial by stopping at a certain level.
407--
408-- | Perform a top down hierarchical recursive partitioning fold of items in
409-- the container using the given function as the partition function.
410--
411-- This will perform a quick sort if the partition function is
412-- 'partitionBy (< pivot)'.
413--
414-- @since 0.7.0
415{-# INLINABLE foldtWith #-}
416foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
417foldtWith level f = undefined
419-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
420-- indicates the level in the tree where the fold would stop.
421--
422-- This will perform a random shuffle if the shuffle function is random.
423-- If we stop at level 0 and repeatedly apply the function then we can do a
424-- bubble sort.
425foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
426foldbWith level f = undefined
427-}
429-- XXX consider the bulk update/accumulation/permutation APIs from vector.
431-------------------------------------------------------------------------------
432-- Random reads and writes
433-------------------------------------------------------------------------------
435-- | /O(1)/ Lookup the element at the given index, starting from 0.
436--
437-- @since 0.8.0
438{-# INLINE getIndex #-}
439getIndex :: Storable a => Array a -> Int -> Maybe a
440getIndex arr i =
441 if i < 0 || i > length arr - 1
442 then Nothing
443 else A.unsafeInlineIO $
444 unsafeWithForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
446{-
447-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
448-- at index @i@ and reading up to @count@ elements in the forward direction
449-- ending at the index @i + count - 1@.
450--
451-- @since 0.7.0
452{-# INLINE readSlice #-}
453readSlice :: (IsStream t, Monad m, Storable a)
454 => Array a -> Int -> Int -> t m a
455readSlice arr i len = undefined
457-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
458-- index @i@ and reading up to @count@ elements in the reverse direction ending
459-- at the index @i - count + 1@.
460--
461-- @since 0.7.0
462{-# INLINE readSliceRev #-}
463readSliceRev :: (IsStream t, Monad m, Storable a)
464 => Array a -> Int -> Int -> t m a
465readSliceRev arr i len = undefined
466-}
468-- | /O(1)/ Write the given element at the given index in the array.
469-- Performs in-place mutation of the array.
470--
471-- /Pre-release/
472{-# INLINE writeIndex #-}
473writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
474writeIndex arr i a = do
475 let maxIndex = length arr - 1
476 if i < 0
477 then error "writeIndex: negative array index"
478 else if i > maxIndex
479 then error $ "writeIndex: specified array index " ++ show i
480 ++ " is beyond the maximum index " ++ show maxIndex
481 else
482 liftIO $ unsafeWithForeignPtr (aStart arr) $ \p ->
483 pokeElemOff p i a
485{-
486-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
487-- starting at index @i@ and writing up to @count@ elements in the forward
488-- direction ending at the index @i + count - 1@.
489--
490-- @since 0.7.0
491{-# INLINE writeSlice #-}
492writeSlice :: (IsStream t, Monad m, Storable a)
493 => Array a -> Int -> Int -> t m a -> m (Array a)
494writeSlice arr i len s = undefined
496-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
497-- starting at index @i@ and writing up to @count@ elements in the reverse
498-- direction ending at the index @i - count + 1@.
499--
500-- @since 0.7.0
501{-# INLINE writeSliceRev #-}
502writeSliceRev :: (IsStream t, Monad m, Storable a)
503 => Array a -> Int -> Int -> t m a -> m (Array a)
504writeSliceRev arr i len s = undefined
505-}
507-------------------------------------------------------------------------------
508-- Transform via stream operations
509-------------------------------------------------------------------------------
511-- for non-length changing operations we can use the original length for
512-- allocation. If we can predict the length then we can use the prediction for
513-- new allocation. Otherwise we can use a hint and adjust dynamically.
515{-
516-- | Transform an array into another array using a pipe transformation
517-- operation.
518--
519-- @since 0.7.0
520{-# INLINE runPipe #-}
521runPipe :: (MonadIO m, Storable a, Storable b)
522 => Pipe m a b -> Array a -> m (Array b)
523runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
524-}
526-- | Transform an array into another array using a stream transformation
527-- operation.
528--
529-- /Pre-release/
530{-# INLINE streamTransform #-}
531streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
532 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
533streamTransform f arr =
534 P.fold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
535 $ f (A.toStream arr)
537-------------------------------------------------------------------------------
538-- Casts
539-------------------------------------------------------------------------------
541-- | Cast an array having elements of type @a@ into an array having elements of
542-- type @b@. The array size must be a multiple of the size of type @b@
543-- otherwise accessing the last element of the array may result into a crash or
544-- a random value.
545--
546-- /Pre-release/
547--
548unsafeCast ::
549#ifdef DEVBUILD
550 Storable b =>
551#endif
552 Array a -> Array b
553unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
555-- | Cast an @Array a@ into an @Array Word8@.
556--
557-- @since 0.8.0
558--
559asBytes :: Array a -> Array Word8
560asBytes = unsafeCast
562-- | Cast an array having elements of type @a@ into an array having elements of
563-- type @b@. The length of the array should be a multiple of the size of the
564-- target element otherwise 'Nothing' is returned.
565--
566-- @since 0.8.0
567--
568cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
569cast arr =
570 let len = A.byteLength arr
571 r = len `mod` sizeOf (undefined :: b)
572 in if r /= 0
573 then Nothing
574 else Just $ unsafeCast arr
576-- | Use an @Array a@ as @Ptr b@.
577--
578-- /Unsafe/
579--
580-- /Pre-release/
581--
582unsafeAsPtr :: Array a -> (Ptr b -> IO c) -> IO c
583unsafeAsPtr Array{..} act = do
584 unsafeWithForeignPtr aStart $ \ptr -> act (castPtr ptr)
586-- | Convert an array of any type into a null terminated CString Ptr.
587--
588-- /Unsafe/
589--
590-- /O(n) Time: (creates a copy of the array)/
591--
592-- /Pre-release/
593--
594unsafeAsCString :: Array a -> (CString -> IO b) -> IO b
595unsafeAsCString arr act = do
596 let Array{..} = asBytes arr <> A.fromList [0]
597 unsafeWithForeignPtr aStart $ \ptr -> act (castPtr ptr)
599-------------------------------------------------------------------------------
600-- Folds
601-------------------------------------------------------------------------------
603-- | Fold an array using a 'Fold'.
604--
605-- /Pre-release/
606{-# INLINE fold #-}
607fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
608fold f arr = P.fold f (A.toStream arr :: Serial.SerialT m a)
610-- | Fold an array using a stream fold operation.
611--
612-- /Pre-release/
613{-# INLINE streamFold #-}
614streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
615streamFold f arr = f (A.toStream arr)