5
5
6
6
7
7
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) {
11
14
// compute bad char table
12
- bad_char_table = {};
13
15
14
16
// Rule 1
15
17
// 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
+ }
17
21
18
22
19
23
// Rule 2
@@ -26,7 +30,7 @@ struct SearchPattern {
26
30
};
27
31
28
32
/* * 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) {
30
34
for (std::size_t h = 0 ; h < haystack.length () - pattern.needle .length () + 1 ;) {
31
35
// Search this placement of the needle.
32
36
bool found = true ;
@@ -53,9 +57,11 @@ std::optional<std::size_t> boyer_moore_horspool(SearchPattern pattern, std::stri
53
57
}
54
58
55
59
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
+
59
65
if (index) {
60
66
std::cout << " found at index " << index.value () << ' \n ' << std::flush;
61
67
} else {
0 commit comments