mirror of
https://github.com/NixOS/nix
synced 2025-06-30 11:43:15 +02:00
Move hilite_all into libutil and rename it to hiliteMatches
The signature was also changed so the function now accepts a vector instead of an iterator
This commit is contained in:
parent
b03fe13b5b
commit
1e0b7cdc3f
3 changed files with 45 additions and 50 deletions
38
src/libutil/fmt.cc
Normal file
38
src/libutil/fmt.cc
Normal file
|
@ -0,0 +1,38 @@
|
|||
#include <regex>
|
||||
|
||||
namespace nix {
|
||||
|
||||
std::string hiliteMatches(const std::string &s, std::vector<std::smatch> matches, std::string prefix, std::string postfix) {
|
||||
// Avoid copy on zero matches
|
||||
if (matches.size() == 0)
|
||||
return s;
|
||||
|
||||
std::sort(matches.begin(), matches.end(), [](const auto &a, const auto &b) {
|
||||
return a.position() < b.position();
|
||||
});
|
||||
|
||||
std::string out;
|
||||
ssize_t last_end = 0;
|
||||
|
||||
for (auto it = matches.begin(); it != matches.end();) {
|
||||
auto m = *it;
|
||||
size_t start = m.position();
|
||||
out.append(s.substr(last_end, m.position() - last_end));
|
||||
// Merge continous matches
|
||||
ssize_t end = start + m.length();
|
||||
while(++it != matches.end() && (*it).position() <= end) {
|
||||
auto n = *it;
|
||||
ssize_t nend = start + (n.position() - start + n.length());
|
||||
if(nend > end)
|
||||
end = nend;
|
||||
}
|
||||
out.append(prefix);
|
||||
out.append(s.substr(start, end - start));
|
||||
out.append(postfix);
|
||||
last_end = end;
|
||||
}
|
||||
out.append(s.substr(last_end));
|
||||
return out;
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue