on a02f2d0 help sign in
537 lines 17 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 -- -- * Search
97 -- , bsearch
98 -- , bsearchIndex
99 -- , find
100 -- , findIndex
101 -- , findIndices
103 , unsafeSlice
105 -- * Immutable Transformations
106 , streamTransform
108 -- * Casting
109 , cast
110 , unsafeCast
111 , unsafeAsPtr
112 , asBytes
113 , unsafeAsCString
115 -- * Folding Arrays
116 , streamFold
117 , fold
118 )
119where
121import Control.Monad (when)
122import Control.Monad.IO.Class (MonadIO(..))
123#if !(MIN_VERSION_base(4,11,0))
124import Data.Semigroup ((<>))
125#endif
126import Data.Word (Word8)
127-- import Data.Functor.Identity (Identity)
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.Type as A
151import qualified Streamly.Internal.Data.Fold as FL
152import qualified Streamly.Internal.Data.Stream.Prelude as P
153import qualified Streamly.Internal.Data.Stream.Serial as Serial
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 m = do
180 when (n < 0) $ error "writeN: negative write count specified"
181 A.fromStreamDN n $ D.toStreamD 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 = P.fold A.write
195-- write m = A.fromStreamD $ D.toStreamD 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-- | > null arr = length arr == 0
250--
251-- /Pre-release/
252{-# INLINE null #-}
253null :: Storable a => Array a -> Bool
254null arr = length arr == 0
256-- | > last arr = getIndex arr (length arr - 1)
257--
258-- /Pre-release/
259{-# INLINE last #-}
260last :: Storable a => Array a -> Maybe a
261last arr = getIndex arr (length arr - 1)
263-------------------------------------------------------------------------------
264-- Folds with Array as the container
265-------------------------------------------------------------------------------
267-- | @writeLastN n@ folds a maximum of @n@ elements from the end of the input
268-- stream to an 'Array'.
269--
270-- @since 0.8.0
271{-# INLINE writeLastN #-}
272writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
273writeLastN n
274 | n <= 0 = fmap (const mempty) FL.drain
275 | otherwise = A.unsafeFreeze <$> Fold step initial done
277 where
279 step (Tuple3' rb rh i) a = do
280 rh1 <- liftIO $ RB.unsafeInsert rb rh a
281 return $ FL.Partial $ Tuple3' rb rh1 (i + 1)
283 initial =
284 let f (a, b) = FL.Partial $ Tuple3' a b (0 :: Int)
285 in fmap f $ liftIO $ RB.new n
287 done (Tuple3' rb rh i) = do
288 arr <- liftIO $ MA.newArray n
289 foldFunc i rh snoc' arr rb
291 snoc' b a = liftIO $ MA.unsafeSnoc b a
293 foldFunc i
294 | i < n = RB.unsafeFoldRingM
295 | otherwise = RB.unsafeFoldRingFullM
297-------------------------------------------------------------------------------
298-- Random Access
299-------------------------------------------------------------------------------
301-------------------------------------------------------------------------------
302-- Searching
303-------------------------------------------------------------------------------
305{-
306-- | Perform a binary search in the array to find an element.
307bsearch :: a -> Array a -> Maybe Bool
308bsearch = undefined
310-- | Perform a binary search in the array to find an element index.
311{-# INLINE elemIndex #-}
312bsearchIndex :: a -> Array a -> Maybe Int
313bsearchIndex elem arr = undefined
315-- find/findIndex etc can potentially be implemented more efficiently on arrays
316-- compared to streams by using SIMD instructions.
318find :: (a -> Bool) -> Array a -> Bool
319find = undefined
321findIndex :: (a -> Bool) -> Array a -> Maybe Int
322findIndex = undefined
324findIndices :: (a -> Bool) -> Array a -> Array Int
325findIndices = undefined
326-}
328-------------------------------------------------------------------------------
329-- Folds
330-------------------------------------------------------------------------------
332-- XXX We can potentially use SIMD instructions on arrays to fold faster.
334-------------------------------------------------------------------------------
335-- Slice and splice
336-------------------------------------------------------------------------------
338-- | /O(1)/ Slice an array in constant time.
339--
340-- Caution: The bounds of the slice are not checked.
341--
342-- /Unsafe/
343--
344-- /Pre-release/
345{-# INLINE unsafeSlice #-}
346unsafeSlice ::
347 forall a. Storable a
348 => Int -- ^ starting index
349 -> Int -- ^ length of the slice
350 -> Array a
351 -> Array a
352unsafeSlice start len (Array fp _) =
353 let size = sizeOf (undefined :: a)
354 fp1 = fp `plusForeignPtr` (start * size)
355 end = unsafeForeignPtrToPtr fp1 `plusPtr` (len * size)
356 in Array fp1 end
358{-
360splitAt :: Int -> Array a -> (Array a, Array a)
361splitAt i arr = undefined
363-- XXX This operation can be performed efficiently via streams.
364-- | Append two arrays together to create a single array.
365splice :: Array a -> Array a -> Array a
366splice arr1 arr2 = undefined
368-}
370-------------------------------------------------------------------------------
371-- Random reads and writes
372-------------------------------------------------------------------------------
374-- | /O(1)/ Lookup the element at the given index, starting from 0.
375--
376-- @since 0.8.0
377{-# INLINE getIndex #-}
378getIndex :: Storable a => Array a -> Int -> Maybe a
379getIndex arr i =
380 if i < 0 || i > length arr - 1
381 then Nothing
382 else unsafeInlineIO $
383 unsafeWithForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
385{-
386-- | @readSlice arr i count@ streams a slice of the array @arr@ starting
387-- at index @i@ and reading up to @count@ elements in the forward direction
388-- ending at the index @i + count - 1@.
389--
390-- @since 0.7.0
391{-# INLINE readSlice #-}
392readSlice :: (IsStream t, Monad m, Storable a)
393 => Array a -> Int -> Int -> t m a
394readSlice arr i len = undefined
396-- | @readSliceRev arr i count@ streams a slice of the array @arr@ starting at
397-- index @i@ and reading up to @count@ elements in the reverse direction ending
398-- at the index @i - count + 1@.
399--
400-- @since 0.7.0
401{-# INLINE readSliceRev #-}
402readSliceRev :: (IsStream t, Monad m, Storable a)
403 => Array a -> Int -> Int -> t m a
404readSliceRev arr i len = undefined
405-}
407{-
408-- | @writeSlice arr i count stream@ writes a stream to the array @arr@
409-- starting at index @i@ and writing up to @count@ elements in the forward
410-- direction ending at the index @i + count - 1@.
411--
412-- @since 0.7.0
413{-# INLINE writeSlice #-}
414writeSlice :: (IsStream t, Monad m, Storable a)
415 => Array a -> Int -> Int -> t m a -> m (Array a)
416writeSlice arr i len s = undefined
418-- | @writeSliceRev arr i count stream@ writes a stream to the array @arr@
419-- starting at index @i@ and writing up to @count@ elements in the reverse
420-- direction ending at the index @i - count + 1@.
421--
422-- @since 0.7.0
423{-# INLINE writeSliceRev #-}
424writeSliceRev :: (IsStream t, Monad m, Storable a)
425 => Array a -> Int -> Int -> t m a -> m (Array a)
426writeSliceRev arr i len s = undefined
427-}
429-------------------------------------------------------------------------------
430-- Transform via stream operations
431-------------------------------------------------------------------------------
433-- for non-length changing operations we can use the original length for
434-- allocation. If we can predict the length then we can use the prediction for
435-- new allocation. Otherwise we can use a hint and adjust dynamically.
437{-
438-- | Transform an array into another array using a pipe transformation
439-- operation.
440--
441-- @since 0.7.0
442{-# INLINE runPipe #-}
443runPipe :: (MonadIO m, Storable a, Storable b)
444 => Pipe m a b -> Array a -> m (Array b)
445runPipe f arr = P.runPipe (toArrayMinChunk (length arr)) $ f (A.read arr)
446-}
448-- | Transform an array into another array using a stream transformation
449-- operation.
450--
451-- /Pre-release/
452{-# INLINE streamTransform #-}
453streamTransform :: forall m a b. (MonadIO m, Storable a, Storable b)
454 => (SerialT m a -> SerialT m b) -> Array a -> m (Array b)
455streamTransform f arr =
456 P.fold (A.toArrayMinChunk (alignment (undefined :: a)) (length arr))
457 $ f (A.toStream arr)
459-------------------------------------------------------------------------------
460-- Casts
461-------------------------------------------------------------------------------
463-- | Cast an array having elements of type @a@ into an array having elements of
464-- type @b@. The array size must be a multiple of the size of type @b@
465-- otherwise accessing the last element of the array may result into a crash or
466-- a random value.
467--
468-- /Pre-release/
469--
470unsafeCast ::
471#ifdef DEVBUILD
472 Storable b =>
473#endif
474 Array a -> Array b
475unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
477-- | Cast an @Array a@ into an @Array Word8@.
478--
479-- @since 0.8.0
480--
481asBytes :: Array a -> Array Word8
482asBytes = unsafeCast
484-- | Cast an array having elements of type @a@ into an array having elements of
485-- type @b@. The length of the array should be a multiple of the size of the
486-- target element otherwise 'Nothing' is returned.
487--
488-- @since 0.8.0
489--
490cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
491cast arr =
492 let len = A.byteLength arr
493 r = len `mod` sizeOf (undefined :: b)
494 in if r /= 0
495 then Nothing
496 else Just $ unsafeCast arr
498-- | Use an @Array a@ as @Ptr b@.
499--
500-- /Unsafe/
501--
502-- /Pre-release/
503--
504unsafeAsPtr :: Array a -> (Ptr b -> IO c) -> IO c
505unsafeAsPtr Array{..} act = do
506 unsafeWithForeignPtr aStart $ \ptr -> act (castPtr ptr)
508-- | Convert an array of any type into a null terminated CString Ptr.
509--
510-- /Unsafe/
511--
512-- /O(n) Time: (creates a copy of the array)/
513--
514-- /Pre-release/
515--
516unsafeAsCString :: Array a -> (CString -> IO b) -> IO b
517unsafeAsCString arr act = do
518 let Array{..} = asBytes arr <> A.fromList [0]
519 unsafeWithForeignPtr aStart $ \ptr -> act (castPtr ptr)
521-------------------------------------------------------------------------------
522-- Folds
523-------------------------------------------------------------------------------
525-- | Fold an array using a 'Fold'.
526--
527-- /Pre-release/
528{-# INLINE fold #-}
529fold :: forall m a b. (MonadIO m, Storable a) => Fold m a b -> Array a -> m b
530fold f arr = P.fold f (A.toStream arr :: Serial.SerialT m a)
532-- | Fold an array using a stream fold operation.
533--
534-- /Pre-release/
535{-# INLINE streamFold #-}
536streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
537streamFold f arr = f (A.toStream arr)