@@ -156,6 +156,7 @@ module Data.Text
156156 , findIndices
157157 , elemIndex
158158 , elemIndices
159+ , count
159160 , countChar
160161
161162 -- * Zipping and unzipping
@@ -899,7 +900,10 @@ tails t | null t = [empty]
899900-- are slices of the original.
900901
901902-- | /O(m)*O(n)/ Break a 'Text' into pieces separated by the first
902−-- 'Text' argument, consuming the delimiter. Examples:
903+-- 'Text' argument, consuming the delimiter. An empty delimiter is
904+-- invalid, and will cause an error to be raised.
905+--
906+-- Examples:
903907--
904908-- > split "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
905909-- > split "aaa" "aaaXaaaXaaaXaaa" == ["","X","X","X",""]
@@ -913,8 +917,8 @@ split :: Text -- ^ Text to split on
913917 -> Text -- ^ Input text
914918 -> [Text]
915919split pat src0
916− | l == 0 = [src0]
917− | l == 1 = splitWith (== (head pat)) src0
920+ | l == 0 = emptyError "split"
921+ | l == 1 = splitWith (== (unsafeHead pat)) src0
918922 | otherwise = go src0
919923 where
920924 l = length pat
@@ -936,7 +940,8 @@ split pat src0
936940-- and consuming the delimiter. The last element of the list contains
937941-- the remaining text after the number of times to split has been
938942-- reached. A value of zero or less for @k@ causes no splitting to
939−-- occur.
943+-- occur. An empty delimiter is invalid, and will cause an error to be
944+-- raised.
940945--
941946-- Examples:
942947--
@@ -952,8 +957,9 @@ splitTimes :: Int -- ^ Maximum number of times to split
952957 -> Text -- ^ Input text
953958 -> [Text]
954959splitTimes k pat src0
955− | k <= 0 || l == 0 = [src0]
956− | otherwise = go k src0
960+ | k <= 0 = [src0]
961+ | l == 0 = emptyError "splitTimes"
962+ | otherwise = go k src0
957963 where
958964 l = length pat
959965 go !i src = search 0 src
@@ -1100,6 +1106,22 @@ elemIndices :: Char -> Text -> [Int]
11001106elemIndices c t = S.elemIndices c (stream t)
11011107{-# INLINE elemIndices #-}
11021108
1109+-- | /O(n*m)/ The 'count' function returns the number of times the
1110+-- query string appears in the given 'Text'.
1111+count :: Text -> Text -> Int
1112+count pat src0
1113+ | l == 0 = length src0 + 1
1114+ | l == 1 = countChar (unsafeHead pat) src0
1115+ | otherwise = go 0 src0
1116+ where
1117+ l = length pat
1118+ go !n src = search src
1119+ where
1120+ search s | null s = n
1121+ | pat `isPrefixOf` s = go (n+1) (drop l s)
1122+ | otherwise = search (unsafeTail s)
1123+{-# INLINE [1] count #-}
1124+
11031125-- | /O(n)/ The 'countChar' function returns the number of times the
11041126-- query element appears in the given 'Text'. Subject to fusion.
11051127countChar :: Char -> Text -> Int