@@ -163,6 +163,8 @@ module Streamly.Streams.StreamD
163163 , splitOn
164164 , splitSuffixOn
165165
166+ , splitInnerBy
167+
166168 -- ** Substreams
167169 , isPrefixOf
168170 , isSubsequenceOf
@@ -1628,6 +1630,59 @@ splitSuffixOn withSep patArr@Array{..} (Fold fstep initial done)
16281630
16291631 stepOuter _ GO_DONE = return Stop
16301632
1633+data SplitState s arr
1634+ = SplitInitial s
1635+ | SplitBuffering s arr
1636+ | SplitSplitting s arr
1637+ | SplitYielding arr (SplitState s arr)
1638+ | SplitFinishing
1639+
1640+-- | Performs infix separator style splitting.
1641+{-# INLINE_NORMAL splitInnerBy #-}
1642+splitInnerBy
1643+ :: Monad m
1644+ => (f a -> m (f a, Maybe (f a))) -- splitter
1645+ -> (f a -> f a -> m (f a)) -- joiner
1646+ -> Stream m (f a)
1647+ -> Stream m (f a)
1648+splitInnerBy splitter joiner (Stream step1 state1) =
1649+ (Stream step (SplitInitial state1))
1650+
1651+ where
1652+
1653+ {-# INLINE_LATE step #-}
1654+ step gst (SplitInitial st) = do
1655+ r <- step1 gst st
1656+ case r of
1657+ Yield x s -> do
1658+ (x1, mx2) <- splitter x
1659+ return $ case mx2 of
1660+ Nothing -> Skip (SplitBuffering s x1)
1661+ Just x2 -> Skip (SplitYielding x1 (SplitSplitting s x2))
1662+ Skip s -> return $ Skip (SplitInitial s)
1663+ Stop -> return $ Stop
1664+
1665+ step gst (SplitBuffering st buf) = do
1666+ r <- step1 gst st
1667+ case r of
1668+ Yield x s -> do
1669+ (x1, mx2) <- splitter x
1670+ buf' <- joiner buf x1
1671+ return $ case mx2 of
1672+ Nothing -> Skip (SplitBuffering s buf')
1673+ Just x2 -> Skip (SplitYielding buf' (SplitSplitting s x2))
1674+ Skip s -> return $ Skip (SplitBuffering s buf)
1675+ Stop -> return $ Skip (SplitYielding buf SplitFinishing)
1676+
1677+ step _ (SplitSplitting st buf) = do
1678+ (x1, mx2) <- splitter buf
1679+ return $ case mx2 of
1680+ Nothing -> Skip $ SplitBuffering st x1
1681+ Just x2 -> Skip $ SplitYielding x1 (SplitSplitting st x2)
1682+
1683+ step _ (SplitYielding x next) = return $ Yield x next
1684+ step _ SplitFinishing = return $ Stop
1685+
16311686------------------------------------------------------------------------------
16321687-- Substreams
16331688------------------------------------------------------------------------------