Make substring search in absl worst-case linear time. absl::StrContains(), absl::StrSplit() with a string delimiter (absl::ByString), absl::StrReplaceAll(), absl::StrContainsIgnoreCase() and absl::Cord::Find() took O(haystack.size() * needle.size()) time in the worst case. For example, searching for "aa...ab" in "aaa...a" makes std::string_view::find() (memchr() for the first byte, then memcmp() for the whole needle, advancing by one byte) compare almost the whole needle at every position. The Boyer-Moore-Horspool searches in StrContainsIgnoreCase() and Cord::Find() are defeated by needles like 'a' x k + 'b' + 'a' x k. With inputs of a few MB, a single call can take minutes of CPU, which is a denial of service risk wherever both strings come from users. This adds strings/internal/string_search.h: - TwoWaySearcher<kIgnoreCase>: the Two-Way algorithm (Crochemore and Perrin, 1991) with a Horspool skip on the last byte, following glibc's two_way_long_needle(). Worst-case O(n + m) time, O(1) extra memory, and optionally ASCII case-insensitive. - NaiveSearchBudget: lets the existing fast paths do at most kMaxShortNeedleSize (64) byte comparisons per haystack byte, plus an initial allowance, before switching to Two-Way. Candidates are probed on their first 16 bytes first; candidates that fail the probe are cheap and are not charged, so typical searches never switch. - FindLongNeedle(): the memchr() + memcmp() search under that budget, for needles of more than 64 bytes. Shorter needles still use std::string_view::find(), whose worst case is bounded by 64 * n. Uses it in: - StrContains(), ByString, StrReplaceAll() and StringReplace(). - StrReplaceAll() with several substitutions, where a long substitution can be searched for again inside its previous occurrence after a shorter one is applied over it: uses the needle's period from Two-Way, so the searches for each substitution take linear total time. The Two-Way state is only built in that case. - StrContainsIgnoreCase(): keeps BMH; needles of more than 64 bytes verify candidates out of line under the budget and switch to case-insensitive Two-Way. - Cord::Find(): keeps the existing chunk-wise search and BMH; needles of more than 64 bytes probe candidates first and, if the budget is exhausted, copy overlapping blocks of the haystack (O(needle.size() + 64 KiB) memory) and search them with Two-Way. Results are unchanged. Typical inputs take the same or less time: long needles are up to 2x faster because the 16-byte probe is inlined, and other cases are within noise. PiperOrigin-RevId: 1029319254
diff --git a/CMake/AbseilDll.cmake b/CMake/AbseilDll.cmake index dddb1a1..6f7082b 100644 --- a/CMake/AbseilDll.cmake +++ b/CMake/AbseilDll.cmake
@@ -364,6 +364,8 @@ "strings/internal/str_join_internal.h" "strings/internal/str_split_internal.h" "strings/internal/string_constant.h" + "strings/internal/string_search.cc" + "strings/internal/string_search.h" "strings/internal/stringify_sink.cc" "strings/internal/stringify_sink.h" "strings/internal/stringify_stream.h"
diff --git a/absl/strings/BUILD.bazel b/absl/strings/BUILD.bazel index f72a9fd..207effc 100644 --- a/absl/strings/BUILD.bazel +++ b/absl/strings/BUILD.bazel
@@ -63,6 +63,7 @@ "internal/memutil.h", "internal/str_join_internal.h", "internal/str_split_internal.h", + "internal/string_search.cc", "internal/stringify_sink.cc", "internal/stringify_sink.h", "match.cc", @@ -79,6 +80,7 @@ "has_absl_stringify.h", "internal/damerau_levenshtein_distance.h", "internal/string_constant.h", + "internal/string_search.h", "match.h", "numbers.h", "str_cat.h", @@ -391,6 +393,36 @@ ) cc_test( + name = "string_search_test", + size = "small", + srcs = ["internal/string_search_test.cc"], + copts = ABSL_TEST_COPTS, + visibility = ["//visibility:private"], + deps = [ + ":cord", + ":string_view", + ":strings", + "@googletest//:gtest", + "@googletest//:gtest_main", + ], +) + +cc_binary( + name = "string_search_benchmark", + testonly = True, + srcs = ["internal/string_search_benchmark.cc"], + copts = ABSL_TEST_COPTS, + tags = ["benchmark"], + visibility = ["//visibility:private"], + deps = [ + ":cord", + ":string_view", + ":strings", + "@google_benchmark//:benchmark_main", + ], +) + +cc_test( name = "memutil_test", size = "small", srcs = [
diff --git a/absl/strings/CMakeLists.txt b/absl/strings/CMakeLists.txt index 8ba84b5..da79b7e 100644 --- a/absl/strings/CMakeLists.txt +++ b/absl/strings/CMakeLists.txt
@@ -38,6 +38,7 @@ "has_absl_stringify.h" "internal/damerau_levenshtein_distance.h" "internal/string_constant.h" + "internal/string_search.h" "match.h" "numbers.h" "str_cat.h" @@ -61,6 +62,7 @@ "internal/stringify_sink.cc" "internal/str_join_internal.h" "internal/str_split_internal.h" + "internal/string_search.cc" "match.cc" "numbers.cc" "str_cat.cc" @@ -310,6 +312,20 @@ absl_cc_test( NAME + string_search_test + SRCS + "internal/string_search_test.cc" + COPTS + ${ABSL_TEST_COPTS} + DEPS + absl::cord + absl::string_view + absl::strings + GTest::gmock_main +) + +absl_cc_test( + NAME memutil_test SRCS "internal/memutil.h"
diff --git a/absl/strings/cord.cc b/absl/strings/cord.cc index d1271f1..c0f2f4d 100644 --- a/absl/strings/cord.cc +++ b/absl/strings/cord.cc
@@ -55,6 +55,7 @@ #include "absl/strings/internal/cord_rep_crc.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cordz_update_tracker.h" +#include "absl/strings/internal/string_search.h" #include "absl/strings/match.h" #include "absl/strings/resize_and_overwrite.h" #include "absl/strings/str_cat.h" @@ -1421,6 +1422,74 @@ } } +// Returns the position of the first occurrence of `needle` at or after `it`, +// or `absl::Cord::CharIterator()` if there is none. Takes worst-case +// O(BytesRemaining(it) + needle.size()) time and O(needle.size()) extra memory: +// copies overlapping blocks of the haystack into a buffer and searches them +// with Two-Way. +absl::Cord::CharIterator FindLinear(absl::Cord::CharIterator it, + absl::string_view needle) { + const size_t m = needle.size(); + const strings_internal::TwoWaySearcher<false> searcher(needle); + // Each block adds at least `m` bytes to the `m - 1` bytes kept from the + // previous block, so searching the blocks takes linear time in total. + const size_t block = (std::max)(m, size_t{1} << 16); + std::string buf; + // The position of `buf[0]`. `it` is the position after the end of `buf`. + absl::Cord::CharIterator buf_start = it; + while (true) { + size_t n = (std::min)(block, BytesRemaining(it)); + while (n > 0) { + absl::string_view chunk = absl::Cord::ChunkRemaining(it); + const size_t k = (std::min)(n, chunk.size()); + buf.append(chunk.data(), k); + absl::Cord::Advance(&it, k); + n -= k; + } + const size_t idx = searcher.Find(buf, needle, 0); + if (idx != absl::string_view::npos) { + absl::Cord::Advance(&buf_start, idx); + return buf_start; + } + if (BytesRemaining(it) == 0) return absl::Cord::CharIterator(); + // Keep the last `m - 1` bytes, which may start an occurrence. + const size_t keep = (std::min)(buf.size(), m - 1); + absl::Cord::Advance(&buf_start, buf.size() - keep); + buf.erase(0, buf.size() - keep); + } +} + +absl::Cord::CharIterator FindLinear(absl::Cord::CharIterator it, + const absl::Cord& needle) { + if (std::optional<absl::string_view> flat = needle.TryFlat()) { + return FindLinear(it, *flat); + } + return FindLinear(it, std::string(needle)); +} + +// Returns the first `kProbeSize` bytes of `needle`, or fewer if its first +// chunk is shorter. +absl::string_view NeedleProbe(absl::string_view needle) { + return needle.substr(0, strings_internal::kProbeSize); +} + +absl::string_view NeedleProbe(const absl::Cord& needle) { + return absl::Cord::ChunkRemaining(needle.char_begin()) + .substr(0, strings_internal::kProbeSize); +} + +// Returns whether `text` starts with the first min(text.size(), probe.size()) +// bytes of `probe`. Candidates that fail this cost at most `kProbeSize` byte +// comparisons, so they never need to be charged to a `NaiveSearchBudget`. +inline bool ProbeMatches(absl::string_view text, absl::string_view probe) { + const size_t k = (std::min)(text.size(), probe.size()); + return text.substr(0, k) == probe.substr(0, k); +} + +// Searches with Boyer-Moore-Horspool. If verifying candidates costs more than +// `strings_internal::kMaxShortNeedleSize` byte comparisons per haystack byte +// (e.g. for needle 'a' x k + 'b' + 'a' x k in haystack 'a' x n), switches to +// FindLinear(), so this takes worst-case linear time. template <typename Needle> absl::Cord::CharIterator FindBMH(absl::Cord::CharIterator it, const Needle& needle) { @@ -1432,6 +1501,9 @@ const uint16_t default_shift = static_cast<uint16_t>(kMaxScan + 1); const unsigned char last_needle = static_cast<unsigned char>(needle[needle_size - 1]); + const absl::string_view needle_probe = NeedleProbe(needle); + const size_t total = BytesRemaining(it); + strings_internal::NaiveSearchBudget budget(needle_size, 0); while (BytesRemaining(it) >= needle_size) { absl::string_view chunk = absl::Cord::ChunkRemaining(it); @@ -1453,7 +1525,21 @@ if (chunk_rem >= needle_size) { last_hay = static_cast<unsigned char>(chunk[idx + needle_size - 1]); } else { - if (!IsPrefixMatch(chunk, idx, chunk_rem, needle)) { + // Most candidates differ from the needle within its first bytes. + if (!ProbeMatches(chunk.substr(idx), needle_probe)) { + absl::Cord::Advance(&it, 1); + continue; + } + // Comparing the prefix costs up to `chunk_rem` byte comparisons, even + // if it matches and the candidate is then rejected by the last byte. + const bool prefix_match = IsPrefixMatch(chunk, idx, chunk_rem, needle); + if (ABSL_PREDICT_FALSE( + !budget.Spend(total - BytesRemaining(it), chunk_rem))) { + // If the prefix matched, `it` itself may still be an occurrence. + if (!prefix_match) absl::Cord::Advance(&it, 1); + return FindLinear(it, needle); + } + if (!prefix_match) { absl::Cord::Advance(&it, 1); continue; } @@ -1471,9 +1557,18 @@ absl::Cord::Advance(&it, shift[last_hay]); continue; } - // Check if this is `needle`. - if (IsSubstringInCordAt(it, needle)) { - return it; + // Check if this is `needle`. Candidates that differ within the probe are + // cheap and need not be charged to the budget. + if (chunk_rem < needle_size || + ProbeMatches(chunk.substr(idx), needle_probe)) { + if (IsSubstringInCordAt(it, needle)) { + return it; + } + if (ABSL_PREDICT_FALSE( + !budget.Spend(total - BytesRemaining(it), needle_size))) { + absl::Cord::Advance(&it, 1); + return FindLinear(it, needle); + } } if (!shift_initialized) { InitShift(shift, needle, default_shift, kMaxScan); @@ -1521,7 +1616,9 @@ // (c) Use string_view::find in each fragment, and specifically handle fragment // boundaries. // -// This currently implements option (b). +// This currently implements option (c). Needles of more than +// `strings_internal::kMaxShortNeedleSize` bytes switch to a linear-time search +// if verifying candidates becomes too expensive. template <typename T> absl::Cord::CharIterator absl::Cord::FindImpl(CharIterator it, const T& needle) const { @@ -1554,6 +1651,14 @@ return FindBMH(it, needle); } + // Budget for needles longer than `kMaxShortNeedleSize`, whose naive search + // would take more than linear time in the worst case. + const bool long_needle = m > strings_internal::kMaxShortNeedleSize; + const absl::string_view needle_probe = + long_needle ? NeedleProbe(needle) : absl::string_view(); + const size_t total = it.chunk_iterator_.bytes_remaining_; + strings_internal::NaiveSearchBudget budget(m, 0); + // Cord is a sequence of chunks. To find `needle` we go chunk by chunk looking // for the first char of needle, up until we have advanced `N` defined as // `haystack.size() - needle.size()`. If we find the first char of needle at @@ -1576,9 +1681,20 @@ if (it.chunk_iterator_.bytes_remaining_ < needle.size()) { break; } - // Check if this is `needle`. - if (IsSubstringInCordAt(it, needle)) { - return it; + // For long needles, candidates that differ within the probe are cheap and + // need not be charged to the budget. + if (!long_needle || + ProbeMatches(haystack_chunk.substr(idx), needle_probe)) { + // Check if this is `needle`. + if (IsSubstringInCordAt(it, needle)) { + return it; + } + if (long_needle && + ABSL_PREDICT_FALSE(!budget.Spend( + total - it.chunk_iterator_.bytes_remaining_, m))) { + Cord::Advance(&it, 1); + return FindLinear(it, needle); + } } // No match, increment the iterator for the next attempt. Cord::Advance(&it, 1);
diff --git a/absl/strings/internal/string_search.cc b/absl/strings/internal/string_search.cc new file mode 100644 index 0000000..ee0712e --- /dev/null +++ b/absl/strings/internal/string_search.cc
@@ -0,0 +1,268 @@ +// Copyright 2026 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "absl/strings/internal/string_search.h" + +#include <algorithm> +#include <cassert> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> + +#include "absl/base/config.h" +#include "absl/strings/ascii.h" +#include "absl/strings/string_view.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace strings_internal { +namespace { + +constexpr size_t kNpos = absl::string_view::npos; + +template <bool kIgnoreCase> +inline unsigned char Fold(unsigned char c) { + if constexpr (kIgnoreCase) { + return static_cast<unsigned char>(absl::ascii_tolower(c)); + } else { + return c; + } +} + +// Computes the maximal suffix of `needle` under the byte order given by +// `less` (applied to folded bytes). Returns the index of the byte before the +// start of that suffix (in [-1, size - 1)), and sets `*period` to the period of +// the suffix. +template <bool kIgnoreCase, typename Less> +ptrdiff_t MaximalSuffix(absl::string_view needle, Less less, + ptrdiff_t* period) { + const ptrdiff_t m = static_cast<ptrdiff_t>(needle.size()); + ptrdiff_t ms = -1; // Index before the start of the current maximal suffix. + ptrdiff_t j = 0; // Start of the candidate suffix being compared, minus 1. + ptrdiff_t k = 1; // Offset within the current comparison. + ptrdiff_t p = 1; // Period of the current maximal suffix. + while (j + k < m) { + const unsigned char a = Fold<kIgnoreCase>( + static_cast<unsigned char>(needle[static_cast<size_t>(j + k)])); + const unsigned char b = Fold<kIgnoreCase>( + static_cast<unsigned char>(needle[static_cast<size_t>(ms + k)])); + if (less(a, b)) { + // The candidate suffix is smaller; skip past it. + j += k; + k = 1; + p = j - ms; + } else if (a == b) { + if (k != p) { + ++k; + } else { + j += p; + k = 1; + } + } else { + // The candidate suffix is larger; it becomes the maximal suffix. + ms = j; + j = ms + 1; + k = 1; + p = 1; + } + } + *period = p; + return ms; +} + +template <bool kIgnoreCase> +bool FoldedEqual(const char* a, const char* b, size_t n) { + if constexpr (kIgnoreCase) { + for (size_t i = 0; i < n; ++i) { + if (Fold<true>(static_cast<unsigned char>(a[i])) != + Fold<true>(static_cast<unsigned char>(b[i]))) { + return false; + } + } + return true; + } else { + return std::memcmp(a, b, n) == 0; + } +} + +} // namespace + +template <bool kIgnoreCase> +TwoWaySearcher<kIgnoreCase>::TwoWaySearcher(absl::string_view needle) { + assert(!needle.empty()); + const size_t m = needle.size(); + // Critical factorization: the larger of the two maximal suffixes (under + // opposite orders) starts at a critical position. + ptrdiff_t p, q; + const ptrdiff_t i1 = MaximalSuffix<kIgnoreCase>( + needle, [](unsigned char a, unsigned char b) { return a < b; }, &p); + const ptrdiff_t i2 = MaximalSuffix<kIgnoreCase>( + needle, [](unsigned char a, unsigned char b) { return a > b; }, &q); + critical_pos_ = static_cast<size_t>((std::max)(i1, i2) + 1); + const size_t period = static_cast<size_t>(i1 > i2 ? p : q); + // `period` is a period of needle[critical_pos_, m), so + // period + critical_pos_ <= m. + if (FoldedEqual<kIgnoreCase>(needle.data(), needle.data() + period, + critical_pos_)) { + // The whole needle has period `period`. This is its smallest period, + // since any period of the needle is a period of the suffix. + periodic_ = true; + shift_ = period; + short_period_ = period <= m / 2 ? period : 0; + } else { + // The smallest period of the needle is larger than + // max(critical_pos_, m - critical_pos_). Use a shift that is safe for both + // parts. + periodic_ = false; + shift_ = (std::max)(critical_pos_, m - critical_pos_) + 1; + short_period_ = 0; + } + // A smaller shift is always safe, so shifts are capped to fit in uint8_t. + constexpr size_t kMaxByteShift = (std::numeric_limits<uint8_t>::max)(); + byte_shift_.fill(static_cast<uint8_t>((std::min)(m, kMaxByteShift))); + for (size_t i = 0; i < m; ++i) { + const uint8_t s = + static_cast<uint8_t>((std::min)(m - i - 1, kMaxByteShift)); + const unsigned char c = static_cast<unsigned char>(needle[i]); + if constexpr (kIgnoreCase) { + byte_shift_[static_cast<unsigned char>(absl::ascii_tolower(c))] = s; + byte_shift_[static_cast<unsigned char>(absl::ascii_toupper(c))] = s; + } else { + byte_shift_[c] = s; + } + } +} + +// Before each Two-Way step, the last byte of the window is checked against +// `byte_shift_` (as in Boyer-Moore-Horspool), which skips most windows in +// typical inputs without affecting the linear worst case. +template <bool kIgnoreCase> +size_t TwoWaySearcher<kIgnoreCase>::Find(absl::string_view haystack, + absl::string_view needle, + size_t pos) const { + const size_t m = needle.size(); + if (pos > haystack.size() || m > haystack.size() - pos) { + return kNpos; + } + const unsigned char* const x = + reinterpret_cast<const unsigned char*>(needle.data()); + // Search in haystack[pos, end), and add `pos` to the result. + const unsigned char* const y = + reinterpret_cast<const unsigned char*>(haystack.data()) + pos; + const size_t last_window = haystack.size() - pos - m; + const size_t c = critical_pos_; + auto eq = [](unsigned char a, unsigned char b) { + return Fold<kIgnoreCase>(a) == Fold<kIgnoreCase>(b); + }; + if (periodic_) { + // After a match of the right part, the first `memory` bytes of the next + // window are known to match. + size_t memory = 0; + for (size_t j = 0; j <= last_window;) { + size_t skip = byte_shift_[y[j + m - 1]]; + if (skip > 0) { + if (memory > 0 && skip < shift_) { + // The needle is periodic, but the last period of the window has a + // byte out of place, so there can be no match until after it. + skip = m - shift_; + } + memory = 0; + j += skip; + continue; + } + // The last byte is known to match. + size_t i = (std::max)(c, memory); + while (i < m - 1 && eq(x[i], y[i + j])) ++i; + if (i < m - 1) { + j += i - c + 1; + memory = 0; + continue; + } + i = c; + while (i > memory && eq(x[i - 1], y[i - 1 + j])) --i; + if (i <= memory) return pos + j; + j += shift_; + memory = m - shift_; + } + } else { + for (size_t j = 0; j <= last_window;) { + const size_t skip = byte_shift_[y[j + m - 1]]; + if (skip > 0) { + j += skip; + continue; + } + // The last byte is known to match. + size_t i = c; + while (i < m - 1 && eq(x[i], y[i + j])) ++i; + if (i < m - 1) { + j += i - c + 1; + continue; + } + i = c; + while (i > 0 && eq(x[i - 1], y[i - 1 + j])) --i; + if (i == 0) return pos + j; + j += shift_; + } + } + return kNpos; +} + +template class TwoWaySearcher<false>; +template class TwoWaySearcher<true>; + +size_t FindLongNeedle(absl::string_view haystack, absl::string_view needle, + size_t pos) { + const size_t n = haystack.size(); + const size_t m = needle.size(); + if (pos > n || m > n - pos) return kNpos; + // Same as libc++'s std::__search_substring(): find the first byte of the + // needle with memchr(), then compare the whole needle with memcmp(). + const char* const begin = haystack.data(); + const char* const last = begin + (n - m); // The last candidate. + const char first = needle[0]; + NaiveSearchBudget budget(m, pos); + const char* p = begin + pos; + while (true) { + p = static_cast<const char*>( + std::memchr(p, first, static_cast<size_t>(last - p) + 1)); + if (p == nullptr) return kNpos; + // Most candidates differ within the first `kProbeSize` bytes, which is an + // inlined comparison, and costs little budget. (m > kProbeSize.) + size_t cost = kProbeSize; + if (std::memcmp(p, needle.data(), kProbeSize) == 0) { + if (std::memcmp(p + kProbeSize, needle.data() + kProbeSize, + m - kProbeSize) == 0) { + return static_cast<size_t>(p - begin); + } + cost = m; + } + const size_t at = static_cast<size_t>(p - begin); + if (ABSL_PREDICT_FALSE(!budget.Spend(at, cost))) { + return TwoWaySearcher<false>(needle).Find(haystack, needle, at + 1); + } + if (p == last) return kNpos; + ++p; + } +} + +size_t FindIgnoreCaseLinear(absl::string_view haystack, + absl::string_view needle, size_t pos) { + if (needle.empty()) return pos <= haystack.size() ? pos : kNpos; + return TwoWaySearcher<true>(needle).Find(haystack, needle, pos); +} + +} // namespace strings_internal +ABSL_NAMESPACE_END +} // namespace absl
diff --git a/absl/strings/internal/string_search.h b/absl/strings/internal/string_search.h new file mode 100644 index 0000000..22432fc --- /dev/null +++ b/absl/strings/internal/string_search.h
@@ -0,0 +1,173 @@ +// Copyright 2026 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Worst-case linear-time substring search. +// +// `std::string_view::find()` (and so `absl::string_view::find()`) in common +// standard libraries looks for the first byte of the needle with memchr() and +// then compares the whole needle with memcmp(), advancing by one byte after +// each mismatch. That takes O(haystack.size() * needle.size()) time in the +// worst case, e.g. for haystack "aaa...a" and needle "aa...ab", which is +// minutes of CPU for inputs of a few MB. +// +// The functions in this file keep that fast path, but bound the work it may do +// to `kMaxShortNeedleSize` byte comparisons per haystack byte. If a search +// exceeds that budget, it continues with the Two-Way algorithm (Crochemore and +// Perrin, "Two-way string-matching", JACM 38(3), 1991), which takes worst-case +// linear time and O(1) extra memory. Typical searches never exceed the budget, +// so they use the same fast path as before. + +#ifndef ABSL_STRINGS_INTERNAL_STRING_SEARCH_H_ +#define ABSL_STRINGS_INTERNAL_STRING_SEARCH_H_ + +#include <array> +#include <cstddef> +#include <cstdint> + +#include "absl/base/config.h" +#include "absl/base/optimization.h" +#include "absl/strings/string_view.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace strings_internal { + +// Needles of at most this many bytes are searched with a naive search, whose +// worst case is bounded by `kMaxShortNeedleSize * haystack.size()` byte +// comparisons. This is also the number of byte comparisons per haystack byte +// that a naive search of a longer needle may do before switching to Two-Way. +inline constexpr size_t kMaxShortNeedleSize = 64; + +// Returns true if a naive search for a needle of `needle_size` bytes, starting +// at `pos` in a haystack of `haystack_size` bytes, takes worst-case linear time +// with a constant factor of at most `kMaxShortNeedleSize`: either the needle is +// short, or there are at most `kMaxShortNeedleSize` candidate positions. This +// is cheap enough to inline. +inline bool NaiveSearchIsFast(size_t needle_size, size_t haystack_size, + size_t pos = 0) { + // If `pos` is huge, the sum wraps around and this returns false, which is + // safe: FindLongNeedle() handles any `pos`. + // Bitwise | avoids a second branch on hot paths. + return (needle_size <= kMaxShortNeedleSize) | + (haystack_size < pos + needle_size + kMaxShortNeedleSize); +} + +// Candidates are first compared on this many bytes. A candidate that differs +// from the needle within them costs `kProbeSize` byte comparisons, so such +// candidates alone never exceed the budget. +inline constexpr size_t kProbeSize = 16; +static_assert(kProbeSize < kMaxShortNeedleSize, + "Failed probes must stay within the budget"); + +// Tracks the work done by a naive search, so that it can switch to a linear +// algorithm before exceeding `kMaxShortNeedleSize` byte comparisons per +// haystack byte (plus an initial allowance of `kMaxShortNeedleSize` failed +// candidates). +class NaiveSearchBudget { + public: + // `start` is the position where the search starts. + explicit NaiveSearchBudget(size_t needle_size, size_t start) + : needle_size_(needle_size), base_(start) {} + + // Records `cost` byte comparisons (by default, a failed candidate) at + // `position`. Returns false if the search should switch to a linear + // algorithm. + bool Spend(size_t position) { return Spend(position, needle_size_); } + bool Spend(size_t position, size_t cost) { + spent_ += cost; + return spent_ <= kMaxShortNeedleSize * (position - base_ + needle_size_); + } + + private: + size_t needle_size_; + size_t base_; + size_t spent_ = 0; +}; + +// Precomputed state for searching for a fixed needle with the Two-Way +// algorithm, plus a Boyer-Moore-Horspool skip on the last byte of each window, +// following two_way_long_needle() in glibc's str-two-way.h. Construction takes +// O(needle.size()) time; each search takes worst-case +// O(haystack.size() - pos + needle.size()) time and O(1) extra memory. +// +// If `kIgnoreCase` is true, bytes are compared after `absl::ascii_tolower()`. +// +// The searcher does not store the needle: callers pass the same needle to +// `Find()` as to the constructor. This lets owners of the needle (e.g. +// `absl::ByString`) be copied and moved without fixing up pointers. +template <bool kIgnoreCase> +class TwoWaySearcher { + public: + // REQUIRES: `!needle.empty()`. + explicit TwoWaySearcher(absl::string_view needle); + + // Returns the position of the first occurrence of `needle` in `haystack` at + // or after `pos`, or `absl::string_view::npos`. + // + // REQUIRES: `needle` is equal to the needle passed to the constructor. + size_t Find(absl::string_view haystack, absl::string_view needle, + size_t pos) const; + + // Returns the smallest period p of the needle (needle[i] == needle[i + p] + // for all valid i), if p <= needle.size() / 2. Otherwise returns 0. + size_t short_period() const { return short_period_; } + + private: + // The needle is split into u = needle[0, critical_pos_) and + // v = needle[critical_pos_, m). Each window is compared on v from left to + // right, then on u from right to left. After a mismatch in u, or a match, + // the window moves by `shift_`. + size_t critical_pos_; + size_t shift_; + // If true, `shift_` is the smallest period of the needle, and after a shift + // the first `needle.size() - shift_` bytes of the window are known to match. + bool periodic_; + size_t short_period_; + // The distance from the last occurrence of each byte value in the needle to + // the end of the needle (or needle.size() if absent), capped at 255. + std::array<uint8_t, 256> byte_shift_; +}; + +extern template class TwoWaySearcher<false>; +extern template class TwoWaySearcher<true>; + +// Same as `haystack.find(needle, pos)`, for needles of more than +// `kMaxShortNeedleSize` bytes. Like libc++, finds the first byte of the needle +// with memchr(), then compares the needle (first `kProbeSize` bytes, then the +// rest). If that would exceed `NaiveSearchBudget`, switches to Two-Way. +size_t FindLongNeedle(absl::string_view haystack, absl::string_view needle, + size_t pos); + +// Same as `haystack.find(needle, pos)`, but takes worst-case +// O((haystack.size() - pos + needle.size()) * kMaxShortNeedleSize) time. +inline size_t Find(absl::string_view haystack, absl::string_view needle, + size_t pos = 0) { + if (ABSL_PREDICT_TRUE( + NaiveSearchIsFast(needle.size(), haystack.size(), pos))) { + return haystack.find(needle, pos); + } + return FindLongNeedle(haystack, needle, pos); +} + +// Returns the position of the first occurrence of `needle` in `haystack` at or +// after `pos`, comparing ASCII case-insensitively, in worst-case +// O(haystack.size() - pos + needle.size()) time. +size_t FindIgnoreCaseLinear(absl::string_view haystack, + absl::string_view needle, size_t pos); + +} // namespace strings_internal +ABSL_NAMESPACE_END +} // namespace absl + +#endif // ABSL_STRINGS_INTERNAL_STRING_SEARCH_H_
diff --git a/absl/strings/internal/string_search_benchmark.cc b/absl/strings/internal/string_search_benchmark.cc new file mode 100644 index 0000000..27e7c01 --- /dev/null +++ b/absl/strings/internal/string_search_benchmark.cc
@@ -0,0 +1,220 @@ +// Copyright 2026 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Benchmarks for substring search through the public APIs that use +// string_search.h. Typical inputs measure the fast path; adversarial inputs +// measure the worst case. + +#include <cstddef> +#include <cstdint> +#include <iterator> +#include <random> +#include <string> +#include <vector> + +#include "absl/strings/cord.h" +#include "absl/strings/match.h" +#include "absl/strings/str_replace.h" +#include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" +#include "benchmark/benchmark.h" + +namespace { + +constexpr size_t kHaystackSize = 64 << 10; + +// Text made of random words, separated by spaces. +std::string TypicalText(size_t size, unsigned seed) { + static const char* const kWords[] = { + "the", "of", "and", "to", "in", "is", "that", + "for", "it", "as", "was", "with", "be", "by", + "on", "not", "he", "this", "are", "or", "his", + "from", "at", "which", "but", "have", "an", "had", + "they", "you", "were", "their", "one", "all", "we", + "can", "her", "has", "there", "been", "if", "more", + "when", "will", "would", "who", "so", "no", "string", + "abseil", "search", "linear", "needle", "haystack", "period"}; + std::mt19937 rng(seed); + std::uniform_int_distribution<size_t> dist(0, std::size(kWords) - 1); + std::string s; + while (s.size() < size) { + s += kWords[dist(rng)]; + s += ' '; + } + s.resize(size); + return s; +} + +// A needle of `size` bytes of typical text that does not occur in the +// haystack (it ends with a byte that does not occur in TypicalText()). +std::string TypicalNeedle(size_t size) { + std::string s = TypicalText(size - 1, 12345); + s += '#'; + return s; +} + +std::string AdversarialNeedle(size_t size) { + return std::string(size - 1, 'a') + "b"; +} + +void BM_StrContainsTypical(benchmark::State& state) { + const std::string haystack = TypicalText(kHaystackSize, 1); + const std::string needle = TypicalNeedle(static_cast<size_t>(state.range(0))); + for (auto _ : state) { + benchmark::DoNotOptimize(haystack); + benchmark::DoNotOptimize(absl::StrContains(haystack, needle)); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(haystack.size())); +} +BENCHMARK(BM_StrContainsTypical)->Arg(4)->Arg(64)->Arg(65)->Arg(256)->Arg(4096); + +void BM_StrContainsEarlyMatch(benchmark::State& state) { + const std::string needle = TypicalNeedle(static_cast<size_t>(state.range(0))); + const std::string haystack = + TypicalText(100, 1) + needle + TypicalText(kHaystackSize, 2); + for (auto _ : state) { + benchmark::DoNotOptimize(haystack); + benchmark::DoNotOptimize(absl::StrContains(haystack, needle)); + } +} +BENCHMARK(BM_StrContainsEarlyMatch)->Arg(65)->Arg(256)->Arg(4096); + +// Many short rows and a needle that is longer than most of them. +void BM_StrContainsShortRows(benchmark::State& state) { + std::vector<std::string> rows; + for (unsigned i = 0; i < 1000; ++i) + rows.push_back(TypicalText(40 + i % 80, i)); + const std::string needle = TypicalNeedle(static_cast<size_t>(state.range(0))); + for (auto _ : state) { + for (const std::string& row : rows) { + benchmark::DoNotOptimize(absl::StrContains(row, needle)); + } + } + state.SetItemsProcessed(state.iterations() * + static_cast<int64_t>(rows.size())); +} +BENCHMARK(BM_StrContainsShortRows)->Arg(65)->Arg(100)->Arg(1000); + +void BM_StrContainsAdversarial(benchmark::State& state) { + const std::string haystack(kHaystackSize, 'a'); + const std::string needle = AdversarialNeedle(static_cast<size_t>(state.range(0))); + for (auto _ : state) { + benchmark::DoNotOptimize(haystack); + benchmark::DoNotOptimize(absl::StrContains(haystack, needle)); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(haystack.size())); +} +BENCHMARK(BM_StrContainsAdversarial)->Arg(64)->Arg(256)->Arg(4096); + +void BM_StrContainsIgnoreCaseTypical(benchmark::State& state) { + const std::string haystack = TypicalText(kHaystackSize, 1); + const std::string needle = TypicalNeedle(static_cast<size_t>(state.range(0))); + for (auto _ : state) { + benchmark::DoNotOptimize(haystack); + benchmark::DoNotOptimize(absl::StrContainsIgnoreCase(haystack, needle)); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(haystack.size())); +} +BENCHMARK(BM_StrContainsIgnoreCaseTypical) + ->Arg(4) + ->Arg(64) + ->Arg(256) + ->Arg(4096); + +void BM_StrContainsIgnoreCaseAdversarial(benchmark::State& state) { + const std::string haystack(kHaystackSize, 'a'); + const size_t k = static_cast<size_t>(state.range(0)) / 2; + const std::string needle = std::string(k, 'a') + "b" + std::string(k, 'a'); + for (auto _ : state) { + benchmark::DoNotOptimize(haystack); + benchmark::DoNotOptimize(absl::StrContainsIgnoreCase(haystack, needle)); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(haystack.size())); +} +BENCHMARK(BM_StrContainsIgnoreCaseAdversarial)->Arg(64)->Arg(256)->Arg(4096); + +void BM_StrSplitTypical(benchmark::State& state) { + const std::string delimiter = TypicalNeedle(static_cast<size_t>(state.range(0))); + std::string text; + for (unsigned i = 0; text.size() < kHaystackSize; ++i) { + text += TypicalText(500, i); + text += delimiter; + } + for (auto _ : state) { + size_t n = 0; + for (absl::string_view piece : absl::StrSplit(text, delimiter)) { + benchmark::DoNotOptimize(piece); + ++n; + } + benchmark::DoNotOptimize(n); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(text.size())); +} +BENCHMARK(BM_StrSplitTypical)->Arg(2)->Arg(64)->Arg(256); + +void BM_StrReplaceAllTypical(benchmark::State& state) { + const std::string old = TypicalNeedle(static_cast<size_t>(state.range(0))); + std::string text; + for (unsigned i = 0; text.size() < kHaystackSize; ++i) { + text += TypicalText(500, i); + text += old; + } + for (auto _ : state) { + benchmark::DoNotOptimize( + absl::StrReplaceAll(text, {{old, "x"}, {"the", "THE"}})); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(text.size())); +} +BENCHMARK(BM_StrReplaceAllTypical)->Arg(2)->Arg(64)->Arg(256); + +absl::Cord MakeFragmentedCord(absl::string_view s, size_t chunk_size) { + absl::Cord cord; + for (size_t i = 0; i < s.size(); i += chunk_size) { + cord.Append(absl::MakeCordFromExternal(s.substr(i, chunk_size), + [](absl::string_view) {})); + } + return cord; +} + +void BM_CordFindTypical(benchmark::State& state) { + const std::string haystack = TypicalText(kHaystackSize, 1); + const absl::Cord cord = MakeFragmentedCord(haystack, 4096); + const std::string needle = TypicalNeedle(static_cast<size_t>(state.range(0))); + for (auto _ : state) { + benchmark::DoNotOptimize(cord.Find(needle)); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(haystack.size())); +} +BENCHMARK(BM_CordFindTypical)->Arg(4)->Arg(64)->Arg(128)->Arg(256)->Arg(4096); + +void BM_CordFindAdversarial(benchmark::State& state) { + const std::string haystack(kHaystackSize, 'a'); + const absl::Cord cord = MakeFragmentedCord(haystack, 4096); + const std::string needle = AdversarialNeedle(static_cast<size_t>(state.range(0))); + for (auto _ : state) { + benchmark::DoNotOptimize(cord.Find(needle)); + } + state.SetBytesProcessed(state.iterations() * + static_cast<int64_t>(haystack.size())); +} +BENCHMARK(BM_CordFindAdversarial)->Arg(64)->Arg(128)->Arg(256)->Arg(4096); + +} // namespace
diff --git a/absl/strings/internal/string_search_test.cc b/absl/strings/internal/string_search_test.cc new file mode 100644 index 0000000..57adf3c --- /dev/null +++ b/absl/strings/internal/string_search_test.cc
@@ -0,0 +1,311 @@ +// Copyright 2026 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "absl/strings/internal/string_search.h" + +#include <algorithm> +#include <cstddef> +#include <random> +#include <string> +#include <utility> +#include <vector> + +#include "gtest/gtest.h" +#include "absl/strings/ascii.h" +#include "absl/strings/cord.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_replace.h" +#include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" + +namespace { + +using absl::strings_internal::FindIgnoreCaseLinear; +using absl::strings_internal::FindLongNeedle; +using absl::strings_internal::kMaxShortNeedleSize; +using absl::strings_internal::TwoWaySearcher; + +constexpr size_t kNpos = absl::string_view::npos; + +size_t NaiveFindIgnoreCase(absl::string_view haystack, absl::string_view needle, + size_t pos) { + if (pos > haystack.size()) return kNpos; + for (size_t i = pos; i + needle.size() <= haystack.size(); ++i) { + if (absl::EqualsIgnoreCase(haystack.substr(i, needle.size()), needle)) { + return i; + } + } + return kNpos; +} + +// Returns a random string over `alphabet`. Small alphabets make matches, +// near-matches and periodic needles common. +std::string RandomString(std::mt19937& rng, absl::string_view alphabet, + size_t size) { + std::uniform_int_distribution<size_t> dist(0, alphabet.size() - 1); + std::string s(size, ' '); + for (char& c : s) c = alphabet[dist(rng)]; + return s; +} + +// Returns a needle that is often periodic: a random string repeated, with an +// occasional mutation. +std::string RandomNeedle(std::mt19937& rng, absl::string_view alphabet, + size_t size) { + std::uniform_int_distribution<size_t> period_dist(1, size); + const std::string unit = RandomString(rng, alphabet, period_dist(rng)); + std::string s; + while (s.size() < size) s += unit; + s.resize(size); + if (rng() % 2 == 0) { + s[rng() % size] = alphabet[rng() % alphabet.size()]; + } + return s; +} + +TEST(TwoWaySearcherTest, MatchesFind) { + std::mt19937 rng(1); + for (absl::string_view alphabet : {"ab", "abc", "abcdefgh"}) { + for (int iter = 0; iter < 3000; ++iter) { + const std::string needle = RandomNeedle(rng, alphabet, 1 + rng() % 12); + const std::string haystack = RandomString(rng, alphabet, rng() % 64); + const TwoWaySearcher<false> searcher(needle); + for (size_t pos = 0; pos <= haystack.size() + 1; ++pos) { + ASSERT_EQ(searcher.Find(haystack, needle, pos), + haystack.find(needle, pos)) + << "haystack=" << haystack << " needle=" << needle + << " pos=" << pos; + } + } + } +} + +TEST(TwoWaySearcherTest, IgnoreCaseMatchesNaive) { + std::mt19937 rng(2); + for (absl::string_view alphabet : {"aA", "aAbB", "aAbBc-"}) { + for (int iter = 0; iter < 3000; ++iter) { + const std::string needle = RandomNeedle(rng, alphabet, 1 + rng() % 12); + const std::string haystack = RandomString(rng, alphabet, rng() % 64); + const TwoWaySearcher<true> searcher(needle); + for (size_t pos = 0; pos <= haystack.size() + 1; ++pos) { + ASSERT_EQ(searcher.Find(haystack, needle, pos), + NaiveFindIgnoreCase(haystack, needle, pos)) + << "haystack=" << haystack << " needle=" << needle + << " pos=" << pos; + } + } + } +} + +TEST(TwoWaySearcherTest, ShortPeriod) { + EXPECT_EQ(TwoWaySearcher<false>("abababab").short_period(), size_t{2}); + EXPECT_EQ(TwoWaySearcher<false>("aaaa").short_period(), size_t{1}); + EXPECT_EQ(TwoWaySearcher<false>("abcab").short_period(), size_t{0}); + EXPECT_EQ(TwoWaySearcher<false>("abcdef").short_period(), size_t{0}); + EXPECT_EQ(TwoWaySearcher<true>("aAaA").short_period(), size_t{1}); +} + +TEST(FindLongNeedleTest, MatchesFind) { + std::mt19937 rng(3); + for (absl::string_view alphabet : {"ab", "abc", "abcdefghijklmnop"}) { + for (int iter = 0; iter < 300; ++iter) { + const size_t m = kMaxShortNeedleSize + 1 + rng() % 200; + const std::string needle = RandomNeedle(rng, alphabet, m); + // Embed occurrences and near-occurrences of the needle. + std::string haystack; + while (haystack.size() < 20000) { + switch (rng() % 3) { + case 0: + haystack += RandomString(rng, alphabet, rng() % 100); + break; + case 1: + haystack += needle.substr(0, rng() % m); + break; + default: + haystack += needle; + } + } + for (size_t pos = 0; pos <= haystack.size() + 1; pos += 1 + rng() % 997) { + ASSERT_EQ(FindLongNeedle(haystack, needle, pos), + haystack.find(needle, pos)) + << "needle=" << needle << " pos=" << pos; + } + } + } +} + +// Adversarial inputs, for which a naive search takes +// O(haystack.size() * needle.size()) time. Each test must finish quickly. +class AdversarialTest : public testing::Test { + protected: + // Large enough that a quadratic search takes minutes, small enough that the + // linear one is fast in sanitizer and unoptimized builds. + static constexpr size_t kHaystackSize = 256 << 10; + static constexpr size_t kNeedleSize = 128 << 10; + + // 'a' x n. + const std::string haystack_ = std::string(kHaystackSize, 'a'); + // 'a' x (m - 1) + 'b': defeats memchr() + memcmp(). + const std::string needle_ab_ = std::string(kNeedleSize - 1, 'a') + "b"; + // 'a' x k + 'b' + 'a' x k: defeats Boyer-Moore-Horspool with first- and + // last-byte prefilters. + const std::string needle_aba_ = std::string(kNeedleSize / 2, 'a') + "b" + + std::string(kNeedleSize / 2, 'a'); + // 'b' + 'a' x (m - 1). + const std::string needle_ba_ = "b" + std::string(kNeedleSize - 1, 'a'); +}; + +TEST_F(AdversarialTest, Find) { + for (const std::string* needle : {&needle_ab_, &needle_aba_, &needle_ba_}) { + EXPECT_EQ(absl::strings_internal::Find(haystack_, *needle), kNpos); + EXPECT_FALSE(absl::StrContains(haystack_, *needle)); + const std::string with_match = haystack_ + *needle; + EXPECT_EQ(absl::strings_internal::Find(with_match, *needle), + haystack_.size()); + EXPECT_TRUE(absl::StrContains(with_match, *needle)); + } +} + +TEST_F(AdversarialTest, StrContainsIgnoreCase) { + for (const std::string* needle : {&needle_ab_, &needle_aba_, &needle_ba_}) { + EXPECT_FALSE(absl::StrContainsIgnoreCase(haystack_, *needle)); + EXPECT_TRUE(absl::StrContainsIgnoreCase( + absl::StrCat(haystack_, absl::AsciiStrToUpper(*needle)), *needle)); + } + EXPECT_EQ(FindIgnoreCaseLinear(haystack_, needle_aba_, 0), kNpos); +} + +TEST_F(AdversarialTest, StrSplit) { + const std::string text = absl::StrCat(haystack_, needle_ab_, haystack_); + std::vector<absl::string_view> pieces = absl::StrSplit(text, needle_ab_); + ASSERT_EQ(pieces.size(), size_t{2}); + EXPECT_EQ(pieces[0], haystack_); + EXPECT_EQ(pieces[1], haystack_); +} + +TEST_F(AdversarialTest, StrReplaceAll) { + EXPECT_EQ(absl::StrReplaceAll(haystack_, {{needle_ab_, "x"}}), haystack_); + EXPECT_EQ(absl::StrReplaceAll(absl::StrCat(haystack_, needle_ab_), + {{needle_ab_, "x"}}), + absl::StrCat(haystack_, "x")); +} + +// With several substitutions, a long substitution can be searched for again +// within its previous occurrence, after a shorter one is applied over it. +TEST(StrReplaceAllTest, OverlappingSubstitutions) { + constexpr size_t kPairs = 1 << 17; + std::string text; + for (size_t i = 0; i < kPairs; ++i) text += "ab"; + std::string long_old; + for (size_t i = 0; i < 10000; ++i) long_old += "ba"; + // "ab" always occurs first, so "ba..." never gets replaced, but it occurs + // at every odd position. + EXPECT_EQ(absl::StrReplaceAll(text, {{"ab", ""}, {long_old, "x"}}), ""); + // Non-periodic long needle, overlapped by "ab" at every occurrence. + const std::string long_old2 = "b" + std::string(100, 'a') + "c"; + std::string text2, expected2; + for (size_t i = 0; i < 5000; ++i) { + text2 += "a" + long_old2; + expected2 += std::string(100, 'a') + "c"; + } + EXPECT_EQ(absl::StrReplaceAll(text2, {{"ab", ""}, {long_old2, "x"}}), + expected2); +} + +TEST(StrReplaceAllTest, MatchesNaive) { + std::mt19937 rng(4); + for (int iter = 0; iter < 150; ++iter) { + const std::string a = RandomNeedle(rng, "ab", 1 + rng() % 3); + const std::string b = + RandomNeedle(rng, "ab", kMaxShortNeedleSize + 1 + rng() % 40); + const std::string text = RandomString(rng, "ab", rng() % 2000) + b + + RandomString(rng, "ab", rng() % 100) + b + a; + // Reference: the specified semantics, applied naively. + std::string expected; + size_t pos = 0; + while (pos < text.size()) { + size_t best = kNpos, best_len = 0; + for (const std::string* old : {&a, &b}) { + const size_t p = text.find(*old, pos); + if (p < best || (p == best && old->size() > best_len)) { + best = p; + best_len = old->size(); + } + } + if (best == kNpos) break; + expected.append(text, pos, best - pos); + expected += best_len == a.size() ? "1" : "2"; + pos = best + best_len; + } + expected.append(text, (std::min)(pos, text.size())); + ASSERT_EQ(absl::StrReplaceAll(text, {{a, "1"}, {b, "2"}}), expected) + << "a=" << a << " b=" << b << " text=" << text; + } +} + +// Returns a Cord with the contents of `s` split into chunks of `chunk_size`. +absl::Cord MakeFragmentedCord(absl::string_view s, size_t chunk_size) { + absl::Cord cord; + for (size_t i = 0; i < s.size(); i += chunk_size) { + cord.Append(absl::MakeCordFromExternal(s.substr(i, chunk_size), + [](absl::string_view) {})); + } + return cord; +} + +TEST_F(AdversarialTest, CordFind) { + for (const std::string* needle : {&needle_ab_, &needle_aba_, &needle_ba_}) { + const absl::Cord needle_cord = MakeFragmentedCord(*needle, 4096); + const std::string with_match = haystack_ + *needle; + for (size_t chunk_size : {size_t{1000}, size_t{1} << 20}) { + const absl::Cord cord = MakeFragmentedCord(haystack_, chunk_size); + EXPECT_EQ(cord.Find(*needle), cord.char_end()); + EXPECT_EQ(cord.Find(needle_cord), cord.char_end()); + const absl::Cord match_cord = MakeFragmentedCord(with_match, chunk_size); + EXPECT_EQ(static_cast<size_t>(absl::Cord::Distance( + match_cord.char_begin(), match_cord.Find(*needle))), + haystack_.size()); + EXPECT_EQ(static_cast<size_t>(absl::Cord::Distance( + match_cord.char_begin(), match_cord.Find(needle_cord))), + haystack_.size()); + } + } +} + +TEST(CordFindTest, MatchesFind) { + std::mt19937 rng(5); + for (int iter = 0; iter < 300; ++iter) { + const size_t m = 2 + rng() % 400; + const std::string needle = RandomNeedle(rng, "ab", m); + std::string haystack; + while (haystack.size() < 30000) { + haystack += rng() % 4 == 0 ? needle : needle.substr(0, rng() % m); + haystack += RandomString(rng, "ab", rng() % 3); + } + const absl::Cord cord = MakeFragmentedCord(haystack, 1 + rng() % 5000); + const size_t expected = haystack.find(needle); + const absl::Cord::CharIterator it = cord.Find(needle); + if (expected == kNpos) { + ASSERT_EQ(it, cord.char_end()); + } else { + ASSERT_EQ( + static_cast<size_t>(absl::Cord::Distance(cord.char_begin(), it)), + expected) + << "needle=" << needle; + } + } +} + +} // namespace
diff --git a/absl/strings/match.cc b/absl/strings/match.cc index ac7cf0d..31d4453 100644 --- a/absl/strings/match.cc +++ b/absl/strings/match.cc
@@ -25,6 +25,7 @@ #include "absl/numeric/bits.h" #include "absl/strings/ascii.h" #include "absl/strings/internal/memutil.h" +#include "absl/strings/internal/string_search.h" #include "absl/strings/string_view.h" namespace absl { @@ -41,12 +42,41 @@ namespace { // For larger haystacks (n >= 256), Case-Insensitive Boyer-Moore-Horspool -// provides sub-linear O(N / M) average-case performance, although it still has -// O(N * M) theoretical worst-case scaling. +// provides sub-linear O(N / M) average-case performance. Its worst case is +// O(N * M), e.g. for needle 'a' x k + 'b' + 'a' x k in haystack 'a' x n, so +// if verifying candidates costs more than `kMaxShortNeedleSize` byte +// comparisons per haystack byte, it switches to case-insensitive Two-Way, +// which takes worst-case O(N + M) time. // Scans the haystack from left to right using a search window of size `m`. // For each window offset, Horspool inspects the rightmost character of the // window (`haystack[pos + m - 1]`) first, enabling multi-byte shifts when // mismatches occur and reducing average search time to O(N / M). +// +// Only needles of more than `kMaxShortNeedleSize` bytes (`kLongNeedle`) can +// exceed the budget, since each verification costs at most `m` byte +// comparisons and is followed by a shift of at least 1. For them, verification +// is done out of line by VerifyLongNeedle(), so that tracking the budget does +// not slow down the loop that skips windows. + +// Result of verifying a candidate window. +enum class Verified { kMatch, kNoMatch, kOverBudget }; + +ABSL_ATTRIBUTE_NOINLINE Verified VerifyLongNeedle(absl::string_view haystack, + absl::string_view needle, + size_t pos, + size_t* verified_bytes) { + const size_t m = needle.size(); + if (EqualsIgnoreCase(haystack.substr(pos + 1, m - 2), + needle.substr(1, m - 2))) { + return Verified::kMatch; + } + *verified_bytes += m; + return *verified_bytes > strings_internal::kMaxShortNeedleSize * (pos + m) + ? Verified::kOverBudget + : Verified::kNoMatch; +} + +template <bool kLongNeedle> ABSL_ATTRIBUTE_NOINLINE bool StrContainsIgnoreCaseBMH( absl::string_view haystack, absl::string_view needle) noexcept { const size_t n = haystack.size(); @@ -70,6 +100,7 @@ // Step 2: Search loop across candidate window offsets. size_t pos = 0; + [[maybe_unused]] size_t verified_bytes = 0; // Only used if kLongNeedle. while (pos <= n - m) { const unsigned char last_hay = static_cast<unsigned char>(haystack[pos + m - 1]); @@ -84,9 +115,22 @@ if (first_hay == first_needle || absl::ascii_tolower(first_hay) == absl::ascii_tolower(first_needle)) { // Check 3: Compare interior (m - 2) bytes. - if (EqualsIgnoreCase(haystack.substr(pos + 1, m - 2), - needle.substr(1, m - 2))) { - return true; + if constexpr (kLongNeedle) { + switch (VerifyLongNeedle(haystack, needle, pos, &verified_bytes)) { + case Verified::kMatch: + return true; + case Verified::kNoMatch: + break; + case Verified::kOverBudget: + // All windows before `pos + 1` have been ruled out. + return strings_internal::FindIgnoreCaseLinear( + haystack, needle, pos + 1) != absl::string_view::npos; + } + } else { + if (EqualsIgnoreCase(haystack.substr(pos + 1, m - 2), + needle.substr(1, m - 2))) { + return true; + } } } } @@ -132,7 +176,10 @@ return false; } - return StrContainsIgnoreCaseBMH(haystack, needle); + if (m > strings_internal::kMaxShortNeedleSize) { + return StrContainsIgnoreCaseBMH<true>(haystack, needle); + } + return StrContainsIgnoreCaseBMH<false>(haystack, needle); } bool StrContainsIgnoreCase(absl::string_view haystack,
diff --git a/absl/strings/match.h b/absl/strings/match.h index 65bd8aa..ce2be10 100644 --- a/absl/strings/match.h +++ b/absl/strings/match.h
@@ -36,6 +36,8 @@ #include <cstring> #include "absl/base/config.h" +#include "absl/base/optimization.h" +#include "absl/strings/internal/string_search.h" #include "absl/strings/string_view.h" namespace absl { @@ -44,9 +46,15 @@ // StrContains() // // Returns whether a given string `haystack` contains the substring `needle`. +// +// Takes worst-case O(haystack.size() + needle.size()) time. inline bool StrContains(absl::string_view haystack, absl::string_view needle) noexcept { - return haystack.find(needle, 0) != haystack.npos; + if (ABSL_PREDICT_TRUE(strings_internal::NaiveSearchIsFast(needle.size(), + haystack.size()))) { + return haystack.find(needle, 0) != haystack.npos; + } + return strings_internal::FindLongNeedle(haystack, needle, 0) != haystack.npos; } inline bool StrContains(absl::string_view haystack, char needle) noexcept {
diff --git a/absl/strings/str_replace.cc b/absl/strings/str_replace.cc index 377e30c..710a385 100644 --- a/absl/strings/str_replace.cc +++ b/absl/strings/str_replace.cc
@@ -14,14 +14,18 @@ #include "absl/strings/str_replace.h" +#include <algorithm> #include <cstddef> #include <initializer_list> +#include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/config.h" #include "absl/base/nullability.h" +#include "absl/base/optimization.h" +#include "absl/strings/internal/string_search.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" @@ -32,6 +36,51 @@ using FixedMapping = std::initializer_list<std::pair<absl::string_view, absl::string_view>>; +namespace { + +// Returns the position of the first occurrence of `sub.old` in `s` at or after +// `pos`, for long needles, given that its previous occurrence is at +// `sub.offset < pos`. +// +// The total time of the calls for one substitution is linear in `s.size()`, +// even though, when another substitution was applied over `sub.offset`, `pos` +// may be within the previous occurrence, so that successive searches overlap. +// In that case, long needles use the needle's period to find the following +// occurrences, as in Two-Way. +size_t FindNextOccurrenceSlow( + absl::string_view s, ViableSubstitution& sub, size_t pos, + std::vector<std::unique_ptr<const TwoWaySearcher<false>>>& searchers) { + const size_t m = sub.old.size(); + if (sub.searcher == nullptr) { + if (pos >= sub.offset + m) { + // This search does not overlap the previous one. + return FindLongNeedle(s, sub.old, pos); + } + searchers.push_back(std::make_unique<const TwoWaySearcher<false>>(sub.old)); + sub.searcher = searchers.back().get(); + } + const size_t p = sub.searcher->short_period(); + if (p > 0) { + // Any occurrence at last < j <= last + m - p would imply a period j - last + // that is a multiple of p, and so an occurrence at last + p. An occurrence + // at last + p only needs its last p bytes to be compared. + size_t last = sub.offset; + while (true) { + if (last + m + p > s.size() || + s.substr(last + m, p) != sub.old.substr(m - p)) { + pos = (std::max)(pos, last + m - p + 1); + break; + } + last += p; + if (last >= pos) return last; + } + } + // Otherwise successive occurrences are more than m / 2 bytes apart. + return sub.searcher->Find(s, sub.old, pos); +} + +} // namespace + // Applies the ViableSubstitutions in subs_ptr to the absl::string_view s, and // stores the result in *result_ptr. Returns the number of substitutions that // occurred. @@ -40,6 +89,8 @@ std::vector<strings_internal::ViableSubstitution>* absl_nonnull subs_ptr, std::string* absl_nonnull result_ptr) { auto& subs = *subs_ptr; + // Owns the ViableSubstitution::searcher objects. + std::vector<std::unique_ptr<const TwoWaySearcher<false>>> searchers; int substitutions = 0; size_t pos = 0; while (!subs.empty()) { @@ -51,7 +102,10 @@ pos = sub.offset + sub.old.size(); substitutions += 1; } - sub.offset = s.find(sub.old, pos); + sub.offset = + ABSL_PREDICT_TRUE(NaiveSearchIsFast(sub.old.size(), s.size(), pos)) + ? s.find(sub.old, pos) + : FindNextOccurrenceSlow(s, sub, pos, searchers); if (sub.offset == s.npos) { subs.pop_back(); } else {
diff --git a/absl/strings/str_replace.h b/absl/strings/str_replace.h index 3af2357..fa00d82 100644 --- a/absl/strings/str_replace.h +++ b/absl/strings/str_replace.h
@@ -47,6 +47,7 @@ #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/nullability.h" +#include "absl/strings/internal/string_search.h" #include "absl/strings/string_view.h" namespace absl { @@ -142,6 +143,11 @@ absl::string_view old; absl::string_view replacement; size_t offset; + // Two-Way search state for `old`, owned by ApplySubstitutions() and built + // only if `old` is long and must be searched for again before the end of + // its previous occurrence. A raw pointer keeps this struct trivially + // copyable, which keeps the insertion sorts cheap. + const TwoWaySearcher<false>* absl_nullable searcher = nullptr; ViableSubstitution(absl::string_view old_str, absl::string_view replacement_str, size_t offset_val) @@ -169,7 +175,7 @@ using std::get; absl::string_view old(get<0>(rep)); - size_t pos = s.find(old); + size_t pos = strings_internal::Find(s, old); if (pos == s.npos) continue; // Ignore attempts to replace "". This condition is almost never true,
diff --git a/absl/strings/str_split.cc b/absl/strings/str_split.cc index abe486b..faf91b9 100644 --- a/absl/strings/str_split.cc +++ b/absl/strings/str_split.cc
@@ -21,6 +21,7 @@ #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" +#include "absl/strings/internal/string_search.h" #include "absl/strings/string_view.h" namespace absl { @@ -54,12 +55,14 @@ return found; } -// Finds using absl::string_view::find(), therefore the length of the found -// delimiter is delimiter.length(). +// Finds the delimiter as a substring, therefore the length of the found +// delimiter is delimiter.length(). Each call takes worst-case linear time in +// the number of bytes between `pos` and the end of the match, so splitting a +// whole text takes linear time. struct LiteralPolicy { static size_t Find(absl::string_view text, absl::string_view delimiter, size_t pos) { - return text.find(delimiter, pos); + return strings_internal::Find(text, delimiter, pos); } static size_t Length(absl::string_view delimiter) { return delimiter.length();