summaryrefslogtreecommitdiffstats
path: root/llvm/lib/Support/StringRef.cpp
diff options
context:
space:
mode:
authorBenjamin Kramer <benny.kra@googlemail.com>2011-10-15 10:08:31 +0000
committerBenjamin Kramer <benny.kra@googlemail.com>2011-10-15 10:08:31 +0000
commit4d681d7dc4904f64073d5bbcaab43a2efccd5a33 (patch)
tree07ffa6754ef55b80f2e1dbf9d65fe26073e30041 /llvm/lib/Support/StringRef.cpp
parentebe13bc3f14ba5e05a443326073de2a9b401bcc7 (diff)
downloadbcm5719-llvm-4d681d7dc4904f64073d5bbcaab43a2efccd5a33.tar.gz
bcm5719-llvm-4d681d7dc4904f64073d5bbcaab43a2efccd5a33.zip
Add a bad char heuristic to StringRef::find.
Based on Horspool's simplified version of Boyer-Moore. We use a constant-sized table of uint8_ts to keep cache thrashing low, needles bigger than 255 bytes are uncommon anyways. The worst case is still O(n*m) but we do a lot better on the average case now. llvm-svn: 142061
Diffstat (limited to 'llvm/lib/Support/StringRef.cpp')
-rw-r--r--llvm/lib/Support/StringRef.cpp29
1 files changed, 26 insertions, 3 deletions
diff --git a/llvm/lib/Support/StringRef.cpp b/llvm/lib/Support/StringRef.cpp
index b5b4f947602..a862ed2fa9c 100644
--- a/llvm/lib/Support/StringRef.cpp
+++ b/llvm/lib/Support/StringRef.cpp
@@ -144,9 +144,32 @@ size_t StringRef::find(StringRef Str, size_t From) const {
size_t N = Str.size();
if (N > Length)
return npos;
- for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
- if (substr(i, N).equals(Str))
- return i;
+
+ // For short haystacks or unsupported needles fall back to the naive algorithm
+ if (Length < 16 || N > 255 || N == 0) {
+ for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
+ if (substr(i, N).equals(Str))
+ return i;
+ return npos;
+ }
+
+ // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
+ uint8_t BadCharSkip[256];
+ std::memset(BadCharSkip, N, 256);
+ for (unsigned i = 0; i != N-1; ++i)
+ BadCharSkip[(uint8_t)Str[i]] = N-1-i;
+
+ unsigned Len = Length, Pos = min(From, Length);
+ while (Len >= N) {
+ if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
+ return Pos;
+
+ // Otherwise skip the appropriate number of bytes.
+ uint8_t Skip = BadCharSkip[(uint8_t)Data[Pos+N-1]];
+ Len -= Skip;
+ Pos += Skip;
+ }
+
return npos;
}
OpenPOWER on IntegriCloud