1{-# LANGUAGE UnboxedTuples #-}
6-- Module : Streamly.Internal.Data.Array.Foreign
7-- Copyright : (c) 2019 Composewell Technologies
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
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
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
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
35module Streamly.Internal.Data.Array.Foreign
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.
60 , A.writeN -- drop new
62 , A.write -- full buffer
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
105 -- * Immutable Transformations
121import Control.Monad (when)
122import Control.Monad.IO.Class (MonadIO(..))
123#if !(MIN_VERSION_base(4,11,0))
124import Data.Semigroup ((<>))
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)
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
168-------------------------------------------------------------------------------
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.
177{-# INLINE fromStreamN #-}
178fromStreamN :: (MonadIO m, Storable a) => Int -> SerialT m a -> m (Array a)
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.
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.
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-------------------------------------------------------------------------------
199-------------------------------------------------------------------------------
201-- | Unfold an array into a stream.
203-- /Since 0.7.0 (Streamly.Memory.Array)/
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.
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.
225{-# INLINE_NORMAL unsafeRead #-}
226unsafeRead :: forall m a. (Monad m, Storable a) => Unfold m (Array a) a
227unsafeRead = Unfold step inject
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.
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
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
253null :: Storable a => Array a -> Bool
254null arr = length arr == 0
256-- | > last arr = getIndex arr (length arr - 1)
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'.
271{-# INLINE writeLastN #-}
272writeLastN :: (Storable a, MonadIO m) => Int -> Fold m a (Array a)
274 | n <= 0 = fmap (const mempty) FL.drain
275 | otherwise = A.unsafeFreeze <$> Fold step initial done
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)
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
294 | i < n = RB.unsafeFoldRingM
295 | otherwise = RB.unsafeFoldRingFullM
297-------------------------------------------------------------------------------
299-------------------------------------------------------------------------------
301-------------------------------------------------------------------------------
303-------------------------------------------------------------------------------
306-- | Perform a binary search in the array to find an element.
307bsearch :: a -> Array a -> Maybe Bool
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
321findIndex :: (a -> Bool) -> Array a -> Maybe Int
324findIndices :: (a -> Bool) -> Array a -> Array Int
325findIndices = undefined
328-------------------------------------------------------------------------------
330-------------------------------------------------------------------------------
332-- XXX We can potentially use SIMD instructions on arrays to fold faster.
334-------------------------------------------------------------------------------
336-------------------------------------------------------------------------------
338-- | /O(1)/ Slice an array in constant time.
340-- Caution: The bounds of the slice are not checked.
345{-# INLINE unsafeSlice #-}
348 => Int -- ^ starting index
349 -> Int -- ^ length of the slice
352unsafeSlice start len (Array fp _) =
353 let size = sizeOf (undefined :: a)
354 fp1 = fp `plusForeignPtr` (start * size)
355 end = unsafeForeignPtrToPtr fp1 `plusPtr` (len * size)
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
370-------------------------------------------------------------------------------
371-- Random reads and writes
372-------------------------------------------------------------------------------
374-- | /O(1)/ Lookup the element at the given index, starting from 0.
377{-# INLINE getIndex #-}
378getIndex :: Storable a => Array a -> Int -> Maybe a
380 if i < 0 || i > length arr - 1
382 else unsafeInlineIO $
383 unsafeWithForeignPtr (aStart arr) $ \p -> Just <$> peekElemOff p i
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@.
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@.
401{-# INLINE readSliceRev #-}
402readSliceRev :: (IsStream t, Monad m, Storable a)
403 => Array a -> Int -> Int -> t m a
404readSliceRev arr i len = undefined
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@.
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@.
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
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.
438-- | Transform an array into another array using a pipe transformation
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)
448-- | Transform an array into another array using a stream transformation
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))
459-------------------------------------------------------------------------------
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
475unsafeCast (Array start end) = Array (castForeignPtr start) (castPtr end)
477-- | Cast an @Array a@ into an @Array Word8@.
481asBytes :: Array a -> Array Word8
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.
490cast :: forall a b. (Storable b) => Array a -> Maybe (Array b)
492 let len = A.byteLength arr
493 r = len `mod` sizeOf (undefined :: b)
496 else Just $ unsafeCast arr
498-- | Use an @Array a@ as @Ptr b@.
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.
512-- /O(n) Time: (creates a copy of the array)/
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-------------------------------------------------------------------------------
523-------------------------------------------------------------------------------
525-- | Fold an array using a '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.
535{-# INLINE streamFold #-}
536streamFold :: (MonadIO m, Storable a) => (SerialT m a -> m b) -> Array a -> m b
537streamFold f arr = f (A.toStream arr)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list