@@ -73,6 +73,7 @@ module Data.Text
7373 , transpose
7474 , reverse
7575 , replace
76+ , replace2
7677
7778 -- ** Case conversion
7879 -- $case
@@ -623,6 +624,31 @@ replace :: Text -- ^ Text to search for
623624replace s d = intercalate d . splitOn s
624625{-# INLINE replace #-}
625626
627+replace2 :: Text -> Text -> Text -> Text
628+replace2 needle@(Text _ _ neeLen)
629+ r@(Text repArr repOff repLen)
630+ haystack@(Text hayArr hayOff hayLen)
631+ | neeLen == 0 = emptyError "replace2"
632+ | len < 0 = overflowError "replace2"
633+ | len == 0 = empty
634+ | L.null ixs = haystack
635+ | otherwise = Text (A.run x) 0 len
636+ where
637+ ixs = indices needle haystack
638+ cnt = L.length ixs
639+ len = hayLen - (neeLen - repLen) * cnt
640+ x = do
641+ marr <- A.new len
642+ let loop is0@(i:is) o d = do
643+ let d0 = d + i - o
644+ d1 = d0 + repLen
645+ A.copyI marr d hayArr (hayOff+o) d0
646+ A.copyI marr d0 repArr repOff d1
647+ loop is (i + neeLen) d1
648+ loop [] o d = A.copyI marr d hayArr (hayOff+o) len
649+ loop ixs 0 0
650+ return marr
651+
626652-- ----------------------------------------------------------------------------
627653-- ** Case conversions (folds)
628654