on master help sign in
Refactor lazy search code to make it easier to read

--HG-- extra : convert_revision : ea0ee86be68524235c98402659d2b7bf7d3b8e1b

commite33c73c730ed7ef693766dd9a8d6a27de63b5f34 authorBryan O'Sullivan <bos@serpentine.com> dateFri 13 Aug 2010, 23:40 (16 years ago) parent5a125ae
1 file changed+14−9
Data/Text/Lazy/Search.hs+14−9
Data/Text/Lazy/Search.hs+14−9
@@ -41,7 +41,7 @@ indices :: Text -- ^ Substring to search for (@needle@)
4141 -> [Int64]
4242indices needle@(Chunk n ns) _haystack@(Chunk k ks)
4343 | nlen <= 0 = []
44− | nlen == 1 = scanOne (nindex 0) 0 k ks
44+ | nlen == 1 = indicesOne (nindex 0) 0 k ks
4545 | otherwise = scan 0 0 k ks
4646 where
4747 scan !g !i x@(T.Text _ _ l) xs
@@ -81,14 +81,6 @@ indices needle@(Chunk n ns) _haystack@(Chunk k ks)
8181 skp' | c == z = nlen - fromIntegral g - 2
8282 | otherwise = skp
8383 xlast = xlen - 1
84− scanOne c i (T.Text oarr ooff olen) os = go 0
85− where
86− go h | h >= olen = case os of
87− Empty -> []
88− Chunk y ys -> scanOne c (i+fromIntegral olen) y ys
89− | on == c = i + fromIntegral h : go (h+1)
90− | otherwise = go (h+1)
91− where on = A.unsafeIndex oarr (ooff+h)
9284 -- | Check whether an attempt to index into the haystack at the
9385 -- given offset would fail.
9486 lackingHay q = go 0
@@ -114,6 +106,19 @@ index (T.Text arr off len) xs !i
114106 Chunk c cs -> index c cs (i-fromIntegral len)
115107 where j = fromIntegral i
116108
109+-- | A variant of 'indices' that scans linearly for a single 'Word16'.
110+indicesOne :: Word16 -> Int64 -> T.Text -> Text -> [Int64]
111+indicesOne c = chunk
112+ where
113+ chunk !i (T.Text oarr ooff olen) os = go 0
114+ where
115+ go h | h >= olen = case os of
116+ Empty -> []
117+ Chunk y ys -> chunk (i+fromIntegral olen) y ys
118+ | on == c = i + fromIntegral h : go (h+1)
119+ | otherwise = go (h+1)
120+ where on = A.unsafeIndex oarr (ooff+h)
121+
117122-- | The number of 'Word16' values in a 'Text'.
118123wordLength :: Text -> Int64
119124wordLength = foldlChunks sumLength 0