on 03218ad help sign in
614 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 , asPtr
133 , asBytes
134 , asCString
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 (withForeignPtr, 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.Data.Array.Foreign.Type (Array(..), length)
162import Streamly.Internal.Data.Fold.Type (Fold(..))
163import Streamly.Internal.Data.Producer.Type (Producer)
164import Streamly.Internal.Data.Stream.Serial (SerialT)
165import Streamly.Internal.Data.Tuple.Strict (Tuple3'(..))
166import Streamly.Internal.Data.Unfold.Type (Unfold(..))
168import qualified Streamly.Internal.Data.Array.Foreign.Mut.Type as MA
169import qualified Streamly.Internal.Data.Array.Foreign.Type as A
170import qualified Streamly.Internal.Data.Fold as FL
171import qualified Streamly.Internal.Data.Stream.Prelude as P
172import qualified Streamly.Internal.Data.Stream.Serial as Serial
173import qualified Streamly.Internal.Data.Stream.StreamD as D
174import qualified Streamly.Internal.Data.Unfold as Unfold
175import qualified Streamly.Internal.Data.Producer.Type as Producer
176import qualified Streamly.Internal.Ring.Foreign as RB
178#if MIN_VERSION_base(4,10,0)
179import Foreign.ForeignPtr (plusForeignPtr)
180#else
181import GHC.Base (Int(..), plusAddr#)
182import GHC.ForeignPtr (ForeignPtr(..))
183plusForeignPtr :: ForeignPtr a -> Int -> ForeignPtr b
184plusForeignPtr (ForeignPtr addr c) (I# d) = ForeignPtr (plusAddr# addr d) c
185#endif
187-------------------------------------------------------------------------------
188-- Construction
189-------------------------------------------------------------------------------
191-- | Create an 'Array' from the first N elements of a stream. The array is
192-- allocated to size N, if the stream terminates before N elements then the
193-- array may hold less than N elements.
194--
195-- /Pre-release/
196{-# INLINE fromStreamN #-}
197fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
198fromStreamN n m = do
199 when (n < 0) $ error "writeN: negative write count specified"
200 A.fromStreamDN n $ D.toStreamD m
202-- | Create an 'Array' from a stream. This is useful when we want to create a
203-- single array from a stream of unknown size. 'writeN' is at least twice
204-- as efficient when the size is already known.
205--
206-- Note that if the input stream is too large memory allocation for the array
207-- may fail. When the stream size is not known, `arraysOf` followed by
208-- processing of indvidual arrays in the resulting stream should be preferred.
209--
210-- /Pre-release/
211{-# INLINE fromStream #-}
212fromStream :: (MonadIO m, Storable a) => SerialT m a -> m (Array a)
213fromStream = P.fold A.write
214-- write m = A.fromStreamD $ D.toStreamD m
216-------------------------------------------------------------------------------
217-- Elimination
218-------------------------------------------------------------------------------
220-- | Unfold an array into a stream.
221--
222-- /Since 0.7.0 (Streamly.Memory.Array)/
223--
224-- @since 0.8.0
225{-# INLINE_NORMAL read #-}
226read :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
227read = Unfold.lmap A.unsafeThaw MA.read
229{-# INLINE_NORMAL producer #-}
230producer :: forall m a. (Monad m, Storable a) => Producer m (Array a) a
231producer = Producer.translate A.unsafeThaw A.unsafeFreeze MA.producer
233-- | Unfold an array into a stream, does not check the end of the array, the
234-- user is responsible for terminating the stream within the array bounds. For
235-- high performance application where the end condition can be determined by
236-- a terminating fold.
237--
238-- Written in the hope that it may be faster than "read", however, in the case
239-- for which this was written, "read" proves to be faster even though the core
240-- generated with unsafeRead looks simpler.
241--
242-- /Pre-release/
243--
244{-# INLINE_NORMAL unsafeRead #-}
245unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
246unsafeRead = Unfold step inject
247 where
249 inject (Array fp _) = return fp
251 {-# INLINE_LATE step #-}
252 step (ForeignPtr p contents) = do
253 -- unsafeInlineIO allows us to run this in Identity monad for pure
254 -- toList/foldr case which makes them much faster due to not
255 -- accumulating the list and fusing better with the pure consumers.
256 --
257 -- This should be safe as the array contents are guaranteed to be
258 -- evaluated/written to before we peek at them.
259 let !x = A.unsafeInlineIO $ do
260 r <- peek (Ptr p)
261 touch contents
262 return r
263 let !(Ptr p1) = Ptr p `plusPtr` sizeOf (undefined :: a)
264 return $ D.Yield x (ForeignPtr p1 contents)
266 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
268-- | > null arr = length arr == 0
269--
270-- /Pre-release/
271{-# INLINE null #-}
272null :: Storable a => Array a -> Bool
273null arr = length arr == 0
275-- | > last arr = getIndex arr (length arr - 1)
276--
277-- /Pre-release/
278{-# INLINE last #-}
279last :: Storable a => Array a -> Maybe a
280last arr = getIndex arr (length arr - 1)
282-------------------------------------------------------------------------------
283-- Folds with Array as the container
284-------------------------------------------------------------------------------
286-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
287-- stream to an 'Array'.
288--
289-- @since 0.8.0
290{-# INLINE writeLastN #-}
291writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
292writeLastN n
293 | n <= 0 = fmap (const mempty) FL.drain
294 | otherwise = A.unsafeFreeze <$> Fold step initial done
296 where
298 step (Tuple3' rb rh i) a = do
299 rh1 <- liftIO $ RB.unsafeInsert rb rh a
300 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
302 initial =
303 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
304 in fmap f $ liftIO $ RB.new n
306 done (Tuple3' rb rh i) = do
307 arr <- liftIO $ MA.newArray n
308 foldFunc i rh snoc' arr rb
310 snoc' b a = liftIO $ MA.unsafeSnoc b a
312 foldFunc i
313 | i < n = RB.unsafeFoldRingM
314 | otherwise = RB.unsafeFoldRingFullM
316-------------------------------------------------------------------------------
317-- Random Access
318-------------------------------------------------------------------------------
320-------------------------------------------------------------------------------
321-- Searching
322-------------------------------------------------------------------------------
324{-
325-- | Perform a binary search in the array to find an element.
326bsearch :: a -> Array a -> Maybe Bool
327bsearch = undefined
329-- | Perform a binary search in the array to find an element index.
330{-# INLINE elemIndex #-}
331bsearchIndex :: a -> Array a -> Maybe Int
332bsearchIndex elem arr = undefined
334-- find/findIndex etc can potentially be implemented more efficiently on arrays
335-- compared to streams by using SIMD instructions.
337find :: (a -> Bool) -> Array a -> Bool
338find = undefined
340findIndex :: (a -> Bool) -> Array a -> Maybe Int
341findIndex = undefined
343findIndices :: (a -> Bool) -> Array a -> Array Int
344findIndices = undefined
345-}
347-------------------------------------------------------------------------------
348-- Folds
349-------------------------------------------------------------------------------
351-- XXX We can potentially use SIMD instructions on arrays to fold faster.
353-------------------------------------------------------------------------------
354-- Slice and splice
355-------------------------------------------------------------------------------
357-- | /O(1)/ Slice an array in constant time.
358--
359-- Caution: The bounds of the slice are not checked.
360--
361-- /Unsafe/
362--
363-- /Pre-release/
364{-# INLINE unsafeSlice #-}
365unsafeSlice ::
366 forall a. Storable a
367 => Int -- ^ starting index
368 -> Int -- ^ length of the slice
369 -> Array a
370 -> Array a
371unsafeSlice start len (Array fp _) =
372 let size = sizeOf (undefined :: a)
373 fp1 = fp `plusForeignPtr` (start * size)
374 end = unsafeForeignPtrToPtr fp1 `plusPtr` (len * size)
375 in Array fp1 end
377{-
379splitAt :: Int -> Array a -> (Array a, Array a)
380splitAt i arr = undefined
382-- XXX This operation can be performed efficiently via streams.
383-- | Append two arrays together to create a single array.
384splice :: Array a -> Array a -> Array a
385splice arr1 arr2 = undefined
387-------------------------------------------------------------------------------
388-- In-place mutation APIs
389-------------------------------------------------------------------------------
391-- | Partition an array into two halves using a partitioning predicate. The
392-- first half retains values where the predicate is 'False' and the second half
393-- retains values where the predicate is 'True'.
394{-# INLINE partitionBy #-}
395partitionBy :: (a -> Bool) -> Array a -> (Array a, Array a)
396partitionBy f arr = undefined
398-- | Shuffle corresponding elements from two arrays using a shuffle function.
399-- If the shuffle function returns 'False' then do nothing otherwise swap the
400-- elements. This can be used in a bottom up fold to shuffle or reorder the
401-- elements.
402shuffleBy :: (a -> a -> m Bool) -> Array a -> Array a -> m (Array a)
403shuffleBy f arr1 arr2 = undefined
405-- XXX we can also make the folds partial by stopping at a certain level.
406--
407-- | Perform a top down hierarchical recursive partitioning fold of items in
408-- the container using the given function as the partition function.
409--
410-- This will perform a quick sort if the partition function is
411-- 'partitionBy (< pivot)'.
412--
413-- @since 0.7.0
414{-# INLINABLE foldtWith #-}
415foldtWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
416foldtWith level f = undefined
418-- | Perform a pairwise bottom up fold recursively merging the pairs. Level
419-- indicates the level in the tree where the fold would stop.
420--
421-- This will perform a random shuffle if the shuffle function is random.
422-- If we stop at level 0 and repeatedly apply the function then we can do a
423-- bubble sort.
424foldbWith :: Int -> (Array a -> Array a -> m (Array a)) -> Array a -> m (Array a)
425foldbWith level f = undefined
426-}
428-- XXX consider the bulk update/accumulation/permutation APIs from vector.
430-------------------------------------------------------------------------------
431-- Random reads and writes
432-------------------------------------------------------------------------------
434-- | /O(1)/ Lookup the element at the given index, starting from 0.
435--
436-- @since 0.8.0
437{-# INLINE getIndex #-}
438getIndex :: Storable a => Array a -> Int -> Maybe a
439getIndex arr i =
440 if i < 0 || i > length arr - 1
441 then Nothing
442 else A.unsafeInlineIO $
443 withForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
445{-
446-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
447-- at index @i@ and reading up to @count@ elements in the forward direction
448-- ending at the index @i + count - 1@.
449--
450-- @since 0.7.0
451{-# INLINE readSlice #-}
452readSlice :: (IsStream t, Monad m, Storable a)
453 => Array a -> Int -> Int -> t m a
454readSlice arr i len = undefined
456-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
457-- index @i@ and reading up to @count@ elements in the reverse direction ending
458-- at the index @i - count + 1@.
459--
460-- @since 0.7.0
461{-# INLINE readSliceRev #-}
462readSliceRev :: (IsStream t, Monad m, Storable a)
463 => Array a -> Int -> Int -> t m a
464readSliceRev arr i len = undefined
465-}
467-- | /O(1)/ Write the given element at the given index in the array.
468-- Performs in-place mutation of the array.
469--
470-- /Pre-release/
471{-# INLINE writeIndex #-}
472writeIndex :: (MonadIO m, Storable a) => Array a -> Int -> a -> m ()
473writeIndex arr i a = do
474 let maxIndex = length arr - 1
475 if i < 0
476 then error "writeIndex: negative array index"
477 else if i > maxIndex
478 then error $ "writeIndex: specified array index " ++ show i
479 ++ " is beyond the maximum index " ++ show maxIndex
480 else
481 liftIO $ withForeignPtr (aStart arr) $ \p ->
482 pokeElemOff p i a
484{-
485-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
486-- starting at index @i@ and writing up to @count@ elements in the forward
487-- direction ending at the index @i + count - 1@.
488--
489-- @since 0.7.0
490{-# INLINE writeSlice #-}
491writeSlice :: (IsStream t, Monad m, Storable a)
492 => Array a -> Int -> Int -> t m a -> m (Array a)
493writeSlice arr i len s = undefined
495-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
496-- starting at index @i@ and writing up to @count@ elements in the reverse
497-- direction ending at the index @i - count + 1@.
498--
499-- @since 0.7.0
500{-# INLINE writeSliceRev #-}
501writeSliceRev :: (IsStream t, Monad m, Storable a)
502 => Array a -> Int -> Int -> t m a -> m (Array a)
503writeSliceRev arr i len s = undefined
504-}
506-------------------------------------------------------------------------------
507-- Transform via stream operations
508-------------------------------------------------------------------------------
510-- for non-length changing operations we can use the original length for
511-- allocation. If we can predict the length then we can use the prediction for
512-- new allocation. Otherwise we can use a hint and adjust dynamically.
514{-
515-- | Transform an array into another array using a pipe transformation
516-- operation.
517--
518-- @since 0.7.0
519{-# INLINE runPipe #-}
520runPipe :: (MonadIO m, Storable a, Storable b)
521 => Pipe m a b -> Array a -> m (Array b)
522runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
523-}
525-- | Transform an array into another array using a stream transformation
526-- operation.
527--
528-- /Pre-release/
529{-# INLINE streamTransform #-}
530streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
531 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
532streamTransform f arr =
533 P.fold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
534 $ f (A.toStream arr)
536-------------------------------------------------------------------------------
537-- Casts
538-------------------------------------------------------------------------------
540-- | Cast an array having elements of type @a@ into an array having elements of
541-- type @b@. The array size must be a multiple of the size of type @b@
542-- otherwise accessing the last element of the array may result into a crash or
543-- a random value.
544--
545-- /Pre-release/
546--
547unsafeCast ::
548#ifdef DEVBUILD
549 Storable b =>
550#endif
551 Array a -> Array b
552unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
554-- | Cast an @Array a@ into an @Array Word8@.
555--
556-- @since 0.8.0
557--
558asBytes :: Array a -> Array Word8
559asBytes = unsafeCast
561-- | Cast an array having elements of type @a@ into an array having elements of
562-- type @b@. The length of the array should be a multiple of the size of the
563-- target element otherwise 'Nothing' is returned.
564--
565-- @since 0.8.0
566--
567cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
568cast arr =
569 let len = A.byteLength arr
570 r = len `mod` sizeOf (undefined :: b)
571 in if r /= 0
572 then Nothing
573 else Just $ unsafeCast arr
575-- | Use an @Array a@ as @Ptr b@.
576--
577-- /Unsafe/
578--
579-- /Pre-release/
580--
581asPtr :: Array a -> (Ptr b -> IO c) -> IO c
582asPtr Array{..} act = do
583 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
585-- | Convert an array of any type into a null terminated CString Ptr.
586--
587-- /Unsafe/
588--
589-- /O(n) Time: (creates a copy of the array)/
590--
591-- /Pre-release/
592--
593asCString :: Array a -> (CString -> IO b) -> IO b
594asCString arr act = do
595 let Array{..} = asBytes arr <> A.fromList [0]
596 withForeignPtr aStart $ \ptr -> act (castPtr ptr)
598-------------------------------------------------------------------------------
599-- Folds
600-------------------------------------------------------------------------------
602-- | Fold an array using a 'Fold'.
603--
604-- /Pre-release/
605{-# INLINE fold #-}
606fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
607fold f arr = P.fold f (A.toStream arr :: Serial.SerialT m a)
609-- | Fold an array using a stream fold operation.
610--
611-- /Pre-release/
612{-# INLINE streamFold #-}
613streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
614streamFold f arr = f (A.toStream arr)