From 59af8caf3b98458760d8145b117d89eca0f97f65 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 12:17:11 +0530 Subject: [PATCH 1/8] Copy only the requested elements in RingArray.Generic.copyToMutArray When the requested range did not wrap around the end of the ring, copyToMutArray still copied from the start index to the end of the ring into an array of the requested length, writing past its end, and then copied a negative number of elements. copyToMutArray 0 2 on a full 5-element ring failed an assertion in debug builds and corrupted memory otherwise. --- core/src/Streamly/Internal/Data/RingArray/Generic.hs | 8 ++++++-- test/Streamly/Test/Data/RingArray/Generic.hs | 10 ++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/core/src/Streamly/Internal/Data/RingArray/Generic.hs b/core/src/Streamly/Internal/Data/RingArray/Generic.hs index d7a62f66f7..2162bcf8bf 100644 --- a/core/src/Streamly/Internal/Data/RingArray/Generic.hs +++ b/core/src/Streamly/Internal/Data/RingArray/Generic.hs @@ -165,8 +165,12 @@ copyToMutArray adj n RingArray{..} = do end = idx + len arr <- MutArray.emptyOf len arr1 <- MutArray.uninit arr len - MutArray.unsafePutSlice ringArr idx arr1 0 (ringMax - idx) - MutArray.unsafePutSlice ringArr 0 arr1 (ringMax - idx) (end - ringMax) + if end <= ringMax + then MutArray.unsafePutSlice ringArr idx arr1 0 len + else do + MutArray.unsafePutSlice ringArr idx arr1 0 (ringMax - idx) + MutArray.unsafePutSlice + ringArr 0 arr1 (ringMax - idx) (end - ringMax) return arr1 -- This would be theoretically slower than toMutArray because of a branch diff --git a/test/Streamly/Test/Data/RingArray/Generic.hs b/test/Streamly/Test/Data/RingArray/Generic.hs index c06b18617e..093429fd98 100644 --- a/test/Streamly/Test/Data/RingArray/Generic.hs +++ b/test/Streamly/Test/Data/RingArray/Generic.hs @@ -149,6 +149,15 @@ testCopyToMutArray = do _ <- RingArray.unsafeInsertRingWith rng 99 MutArray.toList marr `shouldReturn` [3, 4, 5] +-- Copy fewer elements than the ring has, without wrapping around. +testCopyToMutArrayPartial :: IO () +testCopyToMutArrayPartial = do + rng <- fromListLastN 5 [1 .. 5 :: Int] + marr <- RingArray.copyToMutArray 0 2 rng + MutArray.toList marr `shouldReturn` [1, 2] + marr1 <- RingArray.copyToMutArray 1 3 rng + MutArray.toList marr1 `shouldReturn` [2, 3, 4] + testCopyToMutArrayEmpty :: IO () testCopyToMutArrayEmpty = do rng <- RingArray.emptyOf 0 :: IO (RingArray Int) @@ -183,4 +192,5 @@ main = hspec $ do it "toMutArray (wrap around)" testToMutArrayWrap it "toMutArray (empty ring)" testToMutArrayEmpty it "copyToMutArray" testCopyToMutArray + it "copyToMutArray (partial)" testCopyToMutArrayPartial it "copyToMutArray (empty ring)" testCopyToMutArrayEmpty From bc75701fa1a894854c9c8323cc8b24afeb4b31fb Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 12:17:13 +0530 Subject: [PATCH 2/8] Check the bounds before comparing headers in derived deserializeAt With encodeConstrNames, the derived deserializeAt compared the bytes of the constructor names with the buffer without checking that the name length read from the buffer fits in it. With encodeRecordFields, it compared the record header with the buffer without checking that the header fits in the buffer. A truncated or corrupt buffer made it read beyond the end of the buffer. When the constructor name does not fit, raise an error. When the record header does not fit, take the slow path that reads the header field by field with bounds checks. --- core/src/Streamly/Internal/Data/Serialize/TH.hs | 10 +++++++++- .../Streamly/Internal/Data/Serialize/TH/RecHeader.hs | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/core/src/Streamly/Internal/Data/Serialize/TH.hs b/core/src/Streamly/Internal/Data/Serialize/TH.hs index cc0151124c..3dbc5fa933 100644 --- a/core/src/Streamly/Internal/Data/Serialize/TH.hs +++ b/core/src/Streamly/Internal/Data/Serialize/TH.hs @@ -201,7 +201,15 @@ mkDeserializeExpr True False headTy tyOfTy = $(varE _initialOffset) $(varE _arr) $(varE _endOffset) - $(multiIfE (map (guardCon conLen off1) cons ++ [catchAll]))|] + -- xorCmp reads the constructor name without bounds checks, so + -- check that the name fits in the buffer before calling it. + if $(varE off1) + w8_int $(varE conLen) > $(varE _endOffset) + then error + ("deserializeAt: constructor name at offset = " + ++ show $(varE off1) + ++ " exceeds the buffer length = " + ++ show $(varE _endOffset)) + else $(multiIfE (map (guardCon conLen off1) cons ++ [catchAll]))|] catchAll = normalGE diff --git a/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs b/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs index d21c9cf710..cc925fc053 100644 --- a/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs +++ b/core/src/Streamly/Internal/Data/Serialize/TH/RecHeader.hs @@ -395,7 +395,11 @@ mkRecDeserializeExpr initialOff endOff deserializeWithKeys con = do deserializeAt $(varE initialOff) $(varE _arr) $(varE endOff) ($(varP hOff), hlen1 :: Word32) <- deserializeAt hlenOff $(varE _arr) $(varE endOff) - if (hlen1 == $(litIntegral hlen)) && $(xorCmp hval hOff _arr) + -- xorCmp reads the header without bounds checks, so check that the + -- header fits in the buffer before calling it. + if (hlen1 == $(litIntegral hlen)) + && $(varE hOff) + $(litIntegral hlen) <= $(varE endOff) + && $(xorCmp hval hOff _arr) then do let $(varP (makeI 0)) = $(varE initialOff) + From 1c1db8cd120a60e45718c1d2600ef9ec70794d5e Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 12:17:17 +0530 Subject: [PATCH 3/8] Correct RingArray error messages and the moveReverse doc example The replace error message named insert, the eqArray error message named eqArrayN, and the moveReverse doc example defined moveForward. --- core/src/Streamly/Internal/Data/RingArray.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/Streamly/Internal/Data/RingArray.hs b/core/src/Streamly/Internal/Data/RingArray.hs index 0aff643117..f81572c5b6 100644 --- a/core/src/Streamly/Internal/Data/RingArray.hs +++ b/core/src/Streamly/Internal/Data/RingArray.hs @@ -253,7 +253,7 @@ decrHeadByOffset rh rs n = -- the prev (older) item, when the ring head is at the oldest item it will move -- to the newest item. -- --- >>> moveForward = RingArray.moveBy (-1) +-- >>> moveReverse = RingArray.moveBy (-1) -- {-# INLINE moveReverse #-} moveReverse :: forall a. Unbox a => RingArray a -> RingArray a @@ -399,7 +399,7 @@ replace :: forall m a. (MonadIO m, Unbox a) => RingArray a -> a -> m (RingArray replace rb newVal = do -- Note: ring size cannot be zero. when (ringSize rb == 0) $ - error "insert: cannot insert in 0 sized ring" + error "replace: cannot replace in 0 sized ring" old <- unsafeGetRawIndex (ringHead rb) rb liftIO $ pokeAt (ringHead rb) (ringContents rb) newVal pure (moveForward rb, old) @@ -683,7 +683,7 @@ eqArrayN RingArray{..} Array.Array{..} nBytes eqArray :: RingArray a -> Array a -> IO Bool eqArray RingArray{..} Array.Array{..} | arrEnd - arrStart < ringSize = - error "eqArrayN: array is shorter than ring" + error "eqArray: array is shorter than ring" | otherwise = do part1 <- MutByteArray.unsafeByteCmp From 49243f619db03e450d26c35e55519061eda10211 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 12:42:27 +0530 Subject: [PATCH 4/8] Call the inner fold's final in Fold.foldMaybes and foldEithers When a Nothing (foldMaybes) or a Left (foldEithers) input terminated the fold, the state of the inner fold was dropped without calling its final. A resource released in final, e.g. by finallyIO or bracketIO, was not released until GC, or never for a fold with a plain effectful final. For example, folding [Just 1, Nothing] with foldMaybes over a fold whose final writes an IORef returned Nothing without writing the IORef. --- core/src/Streamly/Internal/Data/Fold/Type.hs | 4 +-- test/Streamly/Test/Data/Fold/Type.hs | 29 +++++++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/core/src/Streamly/Internal/Data/Fold/Type.hs b/core/src/Streamly/Internal/Data/Fold/Type.hs index f4483755d7..0c89bffdfc 100644 --- a/core/src/Streamly/Internal/Data/Fold/Type.hs +++ b/core/src/Streamly/Internal/Data/Fold/Type.hs @@ -1843,7 +1843,7 @@ foldMaybes (Fold step1 initial1 extract1 final1) = initial = fmap Just <$> initial1 - step _ Nothing = pure $ Done Nothing + step st Nothing = Done Nothing <$ final1 st step st (Just x) = fmap Just <$> step1 st x extract st = Just <$> extract1 st @@ -1870,7 +1870,7 @@ foldEithers (Fold step1 initial1 extract1 final1) = initial = fmap Right <$> initial1 - step _ (Left x) = pure $ Done (Left x) + step st (Left x) = Done (Left x) <$ final1 st step st (Right x) = fmap Right <$> step1 st x extract st = Right <$> extract1 st diff --git a/test/Streamly/Test/Data/Fold/Type.hs b/test/Streamly/Test/Data/Fold/Type.hs index 695b7aea1c..e8757a0486 100644 --- a/test/Streamly/Test/Data/Fold/Type.hs +++ b/test/Streamly/Test/Data/Fold/Type.hs @@ -12,7 +12,7 @@ module Streamly.Test.Data.Fold.Type import Control.Exception (SomeException, evaluate, try) import Data.Functor.Identity (Identity(..), runIdentity) -import Data.IORef (newIORef, readIORef, modifyIORef') +import Data.IORef (IORef, newIORef, readIORef, modifyIORef') import qualified Streamly.Internal.Data.Fold as Fold import qualified Streamly.Internal.Data.Fold as F import qualified Streamly.Internal.Data.Scanl as Scanl @@ -408,6 +408,31 @@ foldEithers = do (Stream.fromList [Right 1, Right 2, Right 3 :: Either String Int]) r `shouldBe` Right 6 +-- | A fold whose final sets the IORef to True. +finalSetsRef :: IORef Bool -> Fold.Fold IO Int () +finalSetsRef ref = + Fold.Fold + (\s _ -> return (Fold.Partial s)) + (return (Fold.Partial ())) + return + (\_ -> modifyIORef' ref (const True)) + +foldMaybesFinal :: Expectation +foldMaybesFinal = do + ref <- newIORef False + Stream.fold (Fold.foldMaybes (finalSetsRef ref)) + (Stream.fromList [Just 1, Nothing]) + `shouldReturn` Nothing + readIORef ref `shouldReturn` True + +foldEithersFinal :: Expectation +foldEithersFinal = do + ref <- newIORef False + Stream.fold (Fold.foldEithers (finalSetsRef ref)) + (Stream.fromList [Right 1, Left "e" :: Either String Int]) + `shouldReturn` Left "e" + readIORef ref `shouldReturn` True + ------------------------------------------------------------------------------- -- Condition ------------------------------------------------------------------------------- @@ -683,6 +708,8 @@ main = hspec $ do it "foldMaybes" foldMaybes it "foldEithers" foldEithers + it "foldMaybes calls final" foldMaybesFinal + it "foldEithers calls final" foldEithersFinal it "ifThen" ifThen it "split_" split_ prop "many" many From d8f83152d4ae93b17ab2f0570658ed783345cc0f Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 12:42:27 +0530 Subject: [PATCH 5/8] Finalize the source fold in Fold.refold instead of extracting it refold used the deprecated extractM to get the initial value of the Refold, calling the source fold's extract instead of its final. The source fold was never finalized, and refold failed for folds whose extract is an error, e.g. splitWith, split_, concatMap, longest and duplicate. For example, refold Refold.sconcat over splitWith (++) (fromPure [1]) (take 1 (foldl' (++) [])) failed with "splitWith: cannot be used for scanning" instead of folding [[2]] to [1,2]. --- core/src/Streamly/Internal/Data/Fold/Type.hs | 5 +++-- test/Streamly/Test/Data/Fold/Type.hs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/core/src/Streamly/Internal/Data/Fold/Type.hs b/core/src/Streamly/Internal/Data/Fold/Type.hs index 0c89bffdfc..728c84025f 100644 --- a/core/src/Streamly/Internal/Data/Fold/Type.hs +++ b/core/src/Streamly/Internal/Data/Fold/Type.hs @@ -2579,7 +2579,8 @@ refoldMany1 Partial s -> cextract s Done b -> return b --- | Extract the output of a fold and refold it using a 'Refold'. +-- | Finalize a fold without any input and use its output as the initial +-- value of a 'Refold'. -- -- A fusible alternative to 'concatMap'. -- @@ -2587,7 +2588,7 @@ refoldMany1 {-# INLINE refold #-} refold :: Monad m => Refold m b a c -> Fold m a b -> Fold m a c refold (Refold step inject extract) f = - Fold step (extractM f >>= inject) extract extract + Fold step (finalM f >>= inject) extract extract ------------------------------------------------------------------------------ -- morphInner diff --git a/test/Streamly/Test/Data/Fold/Type.hs b/test/Streamly/Test/Data/Fold/Type.hs index e8757a0486..4797e66215 100644 --- a/test/Streamly/Test/Data/Fold/Type.hs +++ b/test/Streamly/Test/Data/Fold/Type.hs @@ -15,6 +15,7 @@ import Data.Functor.Identity (Identity(..), runIdentity) import Data.IORef (IORef, newIORef, readIORef, modifyIORef') import qualified Streamly.Internal.Data.Fold as Fold import qualified Streamly.Internal.Data.Fold as F +import qualified Streamly.Internal.Data.Refold.Type as Refold import qualified Streamly.Internal.Data.Scanl as Scanl import qualified Streamly.Internal.Data.Stream as Stream @@ -494,6 +495,17 @@ groupsOf = do -- Nested application ------------------------------------------------------------------------------- +-- | 'Fold.refold' must finalize the source fold, not extract it. The +-- 'Fold.splitWith' fold has no extract. +refoldFinal :: Expectation +refoldFinal = do + let src = + Fold.splitWith (++) + (Fold.fromPure [1]) (Fold.take 1 (Fold.foldl' (++) [])) + Stream.fold (Fold.refold Refold.sconcat src) + (Stream.fromList [[2 :: Int]]) + `shouldReturn` [1,2] + concatMap :: Expectation concatMap = do r <- Stream.fold @@ -717,6 +729,7 @@ main = hspec $ do it "groupsOf" groupsOf it "concatMap" concatMap it "duplicate" duplicate + it "refold calls final" refoldFinal prop "teeWithFstLength" teeWithFstLength prop "teeWithMinLength1" teeWithMinLength1 prop "teeWithMinLength2" teeWithMinLength2 From 230b3e4df7e4139a59107afc1496c9c7e1dd9ed5 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 12:42:27 +0530 Subject: [PATCH 6/8] Use Fold.foldl' and Fold.foldr' in the toStreamKRev and toStreamK docs The definitions in the docs used Data.Foldable's foldl' and Prelude's foldr, which define functions on Foldable containers, not folds. --- core/src/Streamly/Internal/Data/Fold/Type.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/Streamly/Internal/Data/Fold/Type.hs b/core/src/Streamly/Internal/Data/Fold/Type.hs index 728c84025f..c1604da763 100644 --- a/core/src/Streamly/Internal/Data/Fold/Type.hs +++ b/core/src/Streamly/Internal/Data/Fold/Type.hs @@ -905,7 +905,7 @@ toListRev = foldl' (flip (:)) [] -- | Buffers the input stream to a pure stream in the reverse order of the -- input. -- --- >>> toStreamKRev = Foldable.foldl' (flip StreamK.cons) StreamK.nil +-- >>> toStreamKRev = Fold.foldl' (flip StreamK.cons) StreamK.nil -- -- This is more efficient than 'toStreamK'. toStreamK has exactly the same -- performance as reversing the stream after toStreamKRev. @@ -921,7 +921,7 @@ toStreamKRev = fromScanl Scanl.toStreamKRev -- | A fold that buffers its input to a pure stream. -- --- >>> toStreamK = foldr StreamK.cons StreamK.nil +-- >>> toStreamK = Fold.foldr' StreamK.cons StreamK.nil -- >>> toStreamK = fmap StreamK.reverse Fold.toStreamKRev -- -- /Internal/ From 9f025efbc3878c4f6e861577557ba5f7da800e10 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 17:38:12 +0530 Subject: [PATCH 7/8] Terminate Fold.bracketIO when the inner fold terminates bracketIO stored the result of the inner fold's step, Partial or Done, and always returned Partial. Done was returned only on the next input, which was dropped: Stream.foldBreak with bracketIO over Fold.take 2 on [1..5] left [4,5] instead of [3,4,5]. If the stream ended right after the inner fold terminated, final returned the result without running the release action, which then ran only on GC. --- core/docs/Changelog.md | 2 ++ .../Streamly/Internal/Data/Fold/Exception.hs | 17 ++++++++++---- test/Streamly/Test/Data/Fold/Exception.hs | 23 +++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/core/docs/Changelog.md b/core/docs/Changelog.md index 1b3c1f68bb..bde5e88a3a 100644 --- a/core/docs/Changelog.md +++ b/core/docs/Changelog.md @@ -65,6 +65,8 @@ * Fix `MutArray.appendMax` on a slice returning an array with a capacity beyond its allocation, appending to it could corrupt memory. * Fix `MutArray.createMinOf 0` writing beyond its allocation. +* Fix `Fold.bracketIO` losing the input after the inner fold terminates, + and not running the release action if the stream ends there. ## 0.3.1 (May 2026) diff --git a/core/src/Streamly/Internal/Data/Fold/Exception.hs b/core/src/Streamly/Internal/Data/Fold/Exception.hs index 4e70024600..293b7d6c67 100644 --- a/core/src/Streamly/Internal/Data/Fold/Exception.hs +++ b/core/src/Streamly/Internal/Data/Fold/Exception.hs @@ -138,9 +138,14 @@ bracketIO bef aft bet = Fold step initial extract final res <- initial1 case res of Partial s -> do - s1 <- step1 s a `MC.onException` liftIO (runIOFinalizer ref) - let fld1 = Fold step1 (pure s1) extract1 final1 - pure $ Partial $ Tuple' ref fld1 + r <- step1 s a `MC.onException` liftIO (runIOFinalizer ref) + case r of + Partial s1 -> do + let fld1 = Fold step1 (pure (Partial s1)) extract1 final1 + pure $ Partial $ Tuple' ref fld1 + Done b -> do + liftIO $ runIOFinalizer ref + pure $ Done b Done b -> do liftIO $ runIOFinalizer ref pure $ Done b @@ -156,9 +161,11 @@ bracketIO bef aft bet = Fold step initial extract final case res of Partial s -> do val <- final1 s `MC.onException` liftIO (runIOFinalizer ref) - runIOFinalizer ref + liftIO $ runIOFinalizer ref pure val - Done b -> pure b + Done b -> do + liftIO $ runIOFinalizer ref + pure b -- | Run a side effect whenever the fold stops normally, aborts due to an -- exception or is garbage collected. diff --git a/test/Streamly/Test/Data/Fold/Exception.hs b/test/Streamly/Test/Data/Fold/Exception.hs index 25f43fdee1..b319f550d0 100644 --- a/test/Streamly/Test/Data/Fold/Exception.hs +++ b/test/Streamly/Test/Data/Fold/Exception.hs @@ -49,6 +49,27 @@ bracketIOFold = do val <- readIORef ref val `shouldBe` 2 +-- The fold must stop with the inner fold, without consuming another input, +-- and release the resource. +bracketIOInnerDone :: Expectation +bracketIOInnerDone = do + ref <- newIORef (0 :: Int) + let fld = Fold.bracketIO (return ()) (\_ -> writeIORef ref 1) + (\_ -> Fold.take 2 Fold.toList) + (r, rest) <- Stream.foldBreak fld (Stream.fromList [1..5 :: Int]) + r `shouldBe` [1,2] + Stream.toList rest `shouldReturn` [3,4,5] + readIORef ref `shouldReturn` 1 + +bracketIOInnerDoneAtEnd :: Expectation +bracketIOInnerDoneAtEnd = do + ref <- newIORef (0 :: Int) + let fld = Fold.bracketIO (return ()) (\_ -> writeIORef ref 1) + (\_ -> Fold.take 2 Fold.toList) + r <- Stream.fold fld (Stream.fromList [1,2 :: Int]) + r `shouldBe` [1,2] + readIORef ref `shouldReturn` 1 + onExceptionFold :: Expectation onExceptionFold = do ref <- newIORef (0 :: Int) @@ -72,4 +93,6 @@ main = hspec $ do it "before" beforeFold it "finallyIO" finallyIOFold it "bracketIO" bracketIOFold + it "bracketIO inner fold done" bracketIOInnerDone + it "bracketIO inner fold done at end" bracketIOInnerDoneAtEnd it "onException" onExceptionFold From 2dc4882236525bf1bc07fbe1541af5f7f96368b5 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 14 Oct 2026 17:38:45 +0530 Subject: [PATCH 8/8] Run the Fold.finallyIO action when the inner fold terminates finallyIO ran the action only in final. When the inner fold returned Done from initial or step, e.g. Fold.take 1 on [1,2,3], the action ran only when the IORef holding it was garbage collected. --- core/docs/Changelog.md | 2 ++ .../src/Streamly/Internal/Data/Fold/Exception.hs | 16 ++++++++++------ test/Streamly/Test/Data/Fold/Exception.hs | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/core/docs/Changelog.md b/core/docs/Changelog.md index bde5e88a3a..400d94871a 100644 --- a/core/docs/Changelog.md +++ b/core/docs/Changelog.md @@ -67,6 +67,8 @@ * Fix `MutArray.createMinOf 0` writing beyond its allocation. * Fix `Fold.bracketIO` losing the input after the inner fold terminates, and not running the release action if the stream ends there. +* Fix `Fold.finallyIO` running the action only on GC when the inner fold + terminates. ## 0.3.1 (May 2026) diff --git a/core/src/Streamly/Internal/Data/Fold/Exception.hs b/core/src/Streamly/Internal/Data/Fold/Exception.hs index 293b7d6c67..f002660c9d 100644 --- a/core/src/Streamly/Internal/Data/Fold/Exception.hs +++ b/core/src/Streamly/Internal/Data/Fold/Exception.hs @@ -180,15 +180,19 @@ finallyIO aft (Fold step1 initial1 extract1 final1) = initial = do ref <- liftIO $ newIOFinalizer aft res <- initial1 `MC.onException` liftIO (runIOFinalizer ref) - pure $ case res of - Done b -> Done b - Partial s -> Partial $ Tuple' ref s + case res of + Done b -> do + liftIO $ runIOFinalizer ref + pure $ Done b + Partial s -> pure $ Partial $ Tuple' ref s step (Tuple' ref s) a = do res <- step1 s a `MC.onException` liftIO (runIOFinalizer ref) - pure $ case res of - Done b -> Done b - Partial s1 -> Partial $ Tuple' ref s1 + case res of + Done b -> do + liftIO $ runIOFinalizer ref + pure $ Done b + Partial s1 -> pure $ Partial $ Tuple' ref s1 extract (Tuple' ref s) = extract1 s `MC.onException` liftIO (runIOFinalizer ref) diff --git a/test/Streamly/Test/Data/Fold/Exception.hs b/test/Streamly/Test/Data/Fold/Exception.hs index b319f550d0..659f7c070d 100644 --- a/test/Streamly/Test/Data/Fold/Exception.hs +++ b/test/Streamly/Test/Data/Fold/Exception.hs @@ -37,6 +37,20 @@ finallyIOFold = do val <- readIORef ref val `shouldBe` 1 +finallyIOInnerDone :: Expectation +finallyIOInnerDone = do + ref <- newIORef (0 :: Int) + let fld = Fold.finallyIO (writeIORef ref 1) (Fold.take 1 Fold.drain) + Stream.fold fld (Stream.fromList [1,2,3 :: Int]) + readIORef ref `shouldReturn` 1 + +finallyIOInitDone :: Expectation +finallyIOInitDone = do + ref <- newIORef (0 :: Int) + let fld = Fold.finallyIO (writeIORef ref 1) (Fold.take 0 Fold.drain) + Stream.fold fld (Stream.fromList [1 :: Int]) + readIORef ref `shouldReturn` 1 + bracketIOFold :: Expectation bracketIOFold = do ref <- newIORef (0 :: Int) @@ -92,6 +106,8 @@ main = hspec $ do describe moduleName $ do it "before" beforeFold it "finallyIO" finallyIOFold + it "finallyIO inner fold done" finallyIOInnerDone + it "finallyIO inner fold done in initial" finallyIOInitDone it "bracketIO" bracketIOFold it "bracketIO inner fold done" bracketIOInnerDone it "bracketIO inner fold done at end" bracketIOInnerDoneAtEnd