@@ -1138,21 +1138,17 @@ elemIndices :: Char -> Text -> [Int]
11381138elemIndices c t = S.elemIndices c (stream t)
11391139{-# INLINE elemIndices #-}
11401140
1141−-- | /O(n*m)/ The 'count' function returns the number of times the
1141+-- | /O(n+m)/ The 'count' function returns the number of times the
11421142-- query string appears in the given 'Text'. An empty query string is
11431143-- invalid, and will cause an error to be raised.
1144+--
1145+-- In (unlikely) bad cases, this function's time complexity
1146+-- degenerates towards /O(n*m)/.
11441147count :: Text -> Text -> Int
1145−count pat src0
1146− | null pat = emptyError "count"
1147− | l == 1 = countChar (unsafeHead pat) src0
1148− | otherwise = go 0 src0
1149− where
1150− l = length pat
1151− go !n src = search src
1152− where
1153− search s | null s = n
1154− | pat `isPrefixOf` s = go (n+1) (drop l s)
1155− | otherwise = search (unsafeTail s)
1148+count pat src
1149+ | null pat = emptyError "count"
1150+ | isSingleton pat = countChar (unsafeHead pat) src
1151+ | otherwise = L.length (indices pat src)
11561152{-# INLINE [1] count #-}
11571153
11581154{-# RULES
@@ -1268,13 +1264,15 @@ isSuffixOf a@(Text _aarr _aoff alen) b@(Text barr boff blen) =
12681264 | otherwise = Text barr (boff+d) alen
12691265{-# INLINE isSuffixOf #-}
12701266
1271−-- | /O(n)/ The 'isInfixOf' function takes two 'Text's and returns
1267+-- | /O(n+m)/ The 'isInfixOf' function takes two 'Text's and returns
12721268-- 'True' iff the first is contained, wholly and intact, anywhere
12731269-- within the second.
1270+--
1271+-- In (unlikely) bad cases, this function's time complexity
1272+-- degenerates towards /O(n*m)/.
12741273isInfixOf :: Text -> Text -> Bool
1275−isInfixOf needle haystack = L.any (isPrefixOf needle) (tails haystack)
1274+isInfixOf pat src = null pat || (not . L.null $ indices pat src)
12761275{-# INLINE isInfixOf #-}
1277−-- TODO: a better implementation
12781276
12791277emptyError :: String -> a
12801278emptyError fun = P.error ("Data.Text." ++ fun ++ ": empty input")