on master help sign in
Add snocMay and bytesFree
commit33b7aaf26103a61a6d392258e16d3d59665b864c authorHarendra Kumar <harendra@composewell.com> dateSat 16 Oct 2021, 15:23 (5 years ago) parent8976d8f
1 file changed+25
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+25
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+25
@@ -39,6 +39,7 @@ module Streamly.Internal.Data.Array.Foreign.Mut.Type
3939 , length
4040 , byteLength
4141 , byteCapacity
42+ , bytesFree
4243
4344 -- * Random access
4445 , getIndexUnsafe
@@ -55,6 +56,7 @@ module Streamly.Internal.Data.Array.Foreign.Mut.Type
5556 , snocWith
5657 , snoc
5758 , snocLinear
59+ , snocMay
5860
5961 -- * Casting
6062 , cast
@@ -517,6 +519,19 @@ snocUnsafe :: forall m a. (MonadIO m, Storable a) =>
517519snocUnsafe arr@Array{..} =
518520 snocNewEnd (aEnd `plusPtr` sizeOf (undefined :: a)) arr
519521
522+-- | Like 'snoc' but does not reallocate when pre-allocated array capacity
523+-- becomes full.
524+--
525+-- /Internal/
526+{-# INLINE snocMay #-}
527+snocMay :: forall m a. (MonadIO m, Storable a) =>
528+ Array a -> a -> m (Maybe (Array a))
529+snocMay arr@Array{..} x = liftIO $ do
530+ let newEnd = aEnd `plusPtr` sizeOf (undefined :: a)
531+ if newEnd <= aBound
532+ then Just <$> snocNewEnd newEnd arr x
533+ else return Nothing
534+
520535reallocWith :: forall m a. (MonadIO m , Storable a) =>
521536 String
522537 -> (Int -> Int)
@@ -839,6 +854,16 @@ byteCapacity Array{..} =
839854 len = aBound `minusPtr` p
840855 in assert (len >= 0) len
841856
857+-- | The remaining capacity in the array for appending more elements without
858+-- reallocation.
859+--
860+-- /Pre-release/
861+{-# INLINE bytesFree #-}
862+bytesFree :: Array a -> Int
863+bytesFree Array{..} =
864+ let n = aBound `minusPtr` aEnd
865+ in assert (n >= 0) n
866+
842867-------------------------------------------------------------------------------
843868-- Streams of arrays - Creation
844869-------------------------------------------------------------------------------