@@ -0,0 +1,44 @@
1+{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}
2+
3+module Data.Text.Search where
4+
5+import qualified Data.Text as T ()
6+import qualified Data.Text.Array as A
7+import Data.Word (Word64)
8+import Data.Text.Internal (Text(..))
9+import Data.Bits ((.|.), (.&.))
10+import Data.Text.UnsafeShift (shiftL)
11+
12+indices :: Text -> Text -> [Int]
13+indices _needle@(Text narr noff nlen) _haystack@(Text harr hoff hlen)
14+ | ldiff < 0 = []
15+ | otherwise = outer 0
16+ where
17+ ldiff = hlen - nlen
18+ nlast = nlen - 1
19+ z = nindex nlast
20+ nindex k = A.unsafeIndex narr (noff+k)
21+ hindex k = A.unsafeIndex harr (hoff+k)
22+ (mask :: Word64, skip :: Int) = buildTable 0 0 (nlen-2)
23+ buildTable !i !msk !skp
24+ | i >= nlast = (msk .|. swizzle z, skp)
25+ | otherwise = buildTable (i+1) (msk .|. swizzle c) skp'
26+ where c = nindex i
27+ skp' | c == z = nlen - i - 2
28+ | otherwise = skp
29+ swizzle k = 1 `shiftL` (fromEnum k .&. 0x3f)
30+ outer !i
31+ | i > ldiff = []
32+ | c == z = if candidateMatch 0
33+ then i : outer (i + nlast)
34+ else if nextInPattern
35+ then outer (i + nlen)
36+ else outer (i + skip)
37+ | nextInPattern = outer (i + nlen)
38+ | otherwise = outer (i + 1)
39+ where c = hindex (i+nlast)
40+ candidateMatch j
41+ | j >= nlast = True
42+ | hindex (i+j) /= nindex j = False
43+ | otherwise = candidateMatch (j+1)
44+ nextInPattern = (mask .&. swizzle (hindex (i+nlen))) == 0