From 09090a1c135a4d8193cae26bff76f6863e26ca4b Mon Sep 17 00:00:00 2001 From: tastytea Date: Mon, 24 May 2021 19:57:15 +0200 Subject: [PATCH] Fix bugs in search::context(). - Don't add context if words == 0 - Handle beginning / end of text correctly. --- src/search.cpp | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/search.cpp b/src/search.cpp index b760d9d..8434945 100644 --- a/src/search.cpp +++ b/src/search.cpp @@ -153,27 +153,54 @@ match_context context(const boost::match_results &match, std::uint64_t words) { + if (words == 0) + { + return {}; + } + const auto &prefix{match.prefix().str()}; const auto &suffix{match.suffix().str()}; size_t pos_before{prefix.length()}; size_t pos_after{}; + ++words; while (words != 0) { - if (pos_before != std::string::npos) + if (pos_before != 0) { - pos_before = prefix.rfind(' ', pos_before) - 1; + pos_before = prefix.rfind(' ', pos_before); + if (pos_before != std::string::npos) + { + --pos_before; + } + else + { + pos_before = 0; + } } if (pos_after != std::string::npos) { - pos_after = suffix.find(' ', pos_after) + 1; + pos_after = suffix.find(' ', pos_after); + if (pos_after != std::string::npos) + { + ++pos_after; + } } words -= 1; } - return {prefix.substr(pos_before + 2), suffix.substr(0, pos_after - 1)}; + if (pos_before != 0) + { + pos_before += 2; + } + if (pos_after != std::string::npos) + { + pos_after -= 1; + } + + return {prefix.substr(pos_before), suffix.substr(0, pos_after)}; } std::string headline(const std::string_view prefix)