diff --git a/ZACLib/ZACLib.cpp b/ZACLib/ZACLib.cpp index 5e091a5..045c102 100644 --- a/ZACLib/ZACLib.cpp +++ b/ZACLib/ZACLib.cpp @@ -218,10 +218,23 @@ namespace ZACLib { std::vector Search::Do(const ZAC_SV& input) const { std::vector result; + if (trie.empty()) return result; + int state = 0; for (size_t i = 0; i < input.size(); ++i) { const auto c = static_cast(input[i]); - state = trie[state].next[c]; + + // Allow matching even when Build() has not been called yet. + // In that case transitions can still be -1, so we fall back to + // the fail chain and finally the root instead of indexing trie[-1]. + while (state != 0 && trie[state].next[c] == -1) { + state = trie[state].fail; + } + if (trie[state].next[c] != -1) { + state = trie[state].next[c]; + } else { + state = 0; + } if (trie[state].output_id != Node::kInvalidOutput) { result.push_back(