1{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}
4-- Module : Data.Text.Search
5-- Copyright : (c) Bryan O'Sullivan 2009
8-- Maintainer : bos@serpentine.com, rtomharper@googlemail.com,
10-- Stability : experimental
13-- Fast substring search for 'Text', based on work by Boyer, Moore,
14-- Horspool, Sunday, and Lundh.
18-- * R. S. Boyer, J. S. Moore: A Fast String Searching Algorithm.
19-- Communications of the ACM, 20, 10, 762-772 (1977)
21-- * R. N. Horspool: Practical Fast Searching in Strings. Software -
22-- Practice and Experience 10, 501-506 (1980)
24-- * D. M. Sunday: A Very Fast Substring Search Algorithm.
25-- Communications of the ACM, 33, 8, 132-142 (1990)
27-- * F. Lundh: The Fast Search Algorithm.
28-- <http://effbot.org/zone/stringlib.htm> (2006)
30module Data.Text.Search
35import qualified Data.Text.Array as A
36import Data.Word (Word64)
37import Data.Text.Internal (Text(..))
38import Data.Text.Fusion.Internal (PairS(..))
39import Data.Bits ((.|.), (.&.))
40import Data.Text.UnsafeShift (shiftL)
42-- | /O(n+m)/ Find the offsets of all non-overlapping indices of
43-- @needle@ within @haystack@. The offsets returned represent
44-- locations in the low-level array.
46-- In (unlikely) bad cases, this algorithm's complexity degrades
48indices :: Text -- ^ Substring to search for (@needle@)
49 -> Text -- ^ Text to search in (@haystack@)
51indices _needle@(Text narr noff nlen) _haystack@(Text harr hoff hlen)
52 | nlen == 1 = scanOne (nindex 0)
53 | nlen <= 0 || ldiff < 0 = []
59 nindex k = A.unsafeIndex narr (noff+k)
60 hindex k = A.unsafeIndex harr (hoff+k)
61 hindex' k | k == hlen = 0
62 | otherwise = A.unsafeIndex harr (hoff+k)
63 (mask :: Word64) :*: skip = buildTable 0 0 (nlen-2)
64 buildTable !i !msk !skp
65 | i >= nlast = (msk .|. swizzle z) :*: skp
66 | otherwise = buildTable (i+1) (msk .|. swizzle c) skp'
68 skp' | c == z = nlen - i - 2
70 swizzle k = 1 `shiftL` (fromIntegral k .&. 0x3f)
73 | c == z && candidateMatch 0 = i : scan (i + nlen)
74 | otherwise = scan (i + delta)
75 where c = hindex (i + nlast)
78 | hindex (i+j) /= nindex j = False
79 | otherwise = candidateMatch (j+1)
80 delta | nextInPattern = nlen + 1
83 nextInPattern = mask .&. swizzle (hindex' (i+nlen)) == 0
85 where loop !i | i >= hlen = []
86 | hindex i == c = i : loop (i+1)
87 | otherwise = loop (i+1)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list