@@ -29,7 +29,7 @@ module Streamly.Internal.Data.Array.Foreign.Mut.Type
2929
3030 -- * Resizing
3131 , realloc
32− , shrinkToFit
32+ , rightSize
3333
3434 -- * Size
3535 , length
@@ -533,18 +533,28 @@ realloc i arr =
533533 $ reallocAligned
534534 (sizeOf (undefined :: a)) (alignment (undefined :: a)) i arr
535535
536−-- | Remove the free space from an Array.
537−{-# INLINE shrinkToFit #-}
538−shrinkToFit :: (MonadIO m, Storable a) => Array a -> m (Array a)
539−shrinkToFit arr@Array{..} = do
536+-- | Drop any reserved free space at the end of the array and reallocate it to
537+-- reduce wastage.
538+--
539+-- Up to 25% wastage is allowed to avoid reallocations. If the capacity is
540+-- more than 'largeObjectThreshold' then free space up to the 'blockSize' is
541+-- retained.
542+--
543+-- /Pre-release/
544+{-# INLINE rightSize #-}
545+rightSize :: forall m a. (MonadIO m, Storable a) => Array a -> m (Array a)
546+rightSize arr@Array{..} = do
540547 assert (aEnd <= aBound) (return ())
541548 let start = unsafeForeignPtrToPtr aStart
542− let used = aEnd `minusPtr` start
549+ len = aEnd `minusPtr` start
550+ capacity = aBound `minusPtr` start
551+ target = roundUpLargeArray len
543552 waste = aBound `minusPtr` aEnd
544− -- if used == waste == 0 then do not realloc
545− -- if the wastage is more than 25% of the array then realloc
546− if used < 3 * waste
547− then realloc used arr
553+ assert (target >= len) (return ())
554+ assert (len `mod` sizeOf (undefined :: a) == 0) (return ())
555+ -- We trade off some wastage (25%) to avoid reallocations and copying.
556+ if target < capacity && len < 3 * waste
557+ then realloc target arr
548558 else return arr
549559
550560-------------------------------------------------------------------------------
@@ -1106,7 +1116,7 @@ writeWith alignSize elemCount =
11061116 (sizeOf (undefined :: a)) alignSize newSize arr
11071117 insertElem arr1 x
11081118 step arr x = insertElem arr x
1109− extract = liftIO . shrinkToFit
1119+ extract = liftIO . rightSize
11101120
11111121-- | Fold the whole input to a single array.
11121122--