Skip to content

Commit 2dd4710

Browse files
committed
Add compile time evaluation
1 parent d7e86fa commit 2dd4710

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

boyer_moore_horspool.cpp

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,19 @@
55

66

77
struct SearchPattern {
8-
std::string_view needle;
9-
std::array<char, 256> bad_char_table;
10-
SearchPattern(const std::string_view needle) : needle(needle) {
8+
constexpr static std::size_t num_chars{ 256 };
9+
const std::string_view needle;
10+
std::array<char, num_chars> bad_char_table{};
11+
12+
constexpr SearchPattern(const std::string_view needle) noexcept
13+
: needle(needle) {
1114
// compute bad char table
12-
bad_char_table = {};
1315

1416
// Rule 1
1517
// Characters not in the needle jump the length of the needle.
16-
bad_char_table.fill(needle.length());
18+
for (std::size_t i = 0; i < num_chars; i++) {
19+
bad_char_table[i] = needle.length();
20+
}
1721

1822

1923
// Rule 2
@@ -26,7 +30,7 @@ struct SearchPattern {
2630
};
2731

2832
/** Returns index of first occurrance of pattern in haystack. */
29-
std::optional<std::size_t> boyer_moore_horspool(SearchPattern pattern, std::string_view haystack) {
33+
constexpr std::optional<std::size_t> boyer_moore_horspool(SearchPattern pattern, std::string_view haystack) {
3034
for (std::size_t h = 0; h < haystack.length() - pattern.needle.length() + 1;) {
3135
// Search this placement of the needle.
3236
bool found = true;
@@ -53,9 +57,11 @@ std::optional<std::size_t> boyer_moore_horspool(SearchPattern pattern, std::stri
5357
}
5458

5559
int main() {
56-
auto needle = SearchPattern{ "abc" };
57-
auto haystack = "aa abc ddef";
58-
auto index = boyer_moore_horspool(needle, haystack);
60+
constexpr SearchPattern needle{ "abc" };
61+
constexpr auto haystack = "aa abc ddef";
62+
constexpr auto index = boyer_moore_horspool(needle, haystack);
63+
static_assert(index == 3, "index is supposed to be 3!");
64+
5965
if (index) {
6066
std::cout << "found at index " << index.value() << '\n' << std::flush;
6167
} else {

0 commit comments

Comments
 (0)