| 1 | /* |
| 2 | SPDX-FileCopyrightText: 2007 Sebastian Pipping <webmaster@hartwork.org> |
| 3 | |
| 4 | SPDX-License-Identifier: MIT |
| 5 | */ |
| 6 | |
| 7 | #include "wildcardmatcher.h" |
| 8 | |
| 9 | using namespace KSyntaxHighlighting; |
| 10 | |
| 11 | #include <QChar> |
| 12 | |
| 13 | namespace |
| 14 | { |
| 15 | bool wildcardMatch(QStringView candidate, QStringView wildcard, int candidatePosFromRight, int wildcardPosFromRight) |
| 16 | { |
| 17 | for (; wildcardPosFromRight >= 0; wildcardPosFromRight--) { |
| 18 | const auto ch = wildcard.at(n: wildcardPosFromRight).unicode(); |
| 19 | switch (ch) { |
| 20 | case L'*': |
| 21 | if (candidatePosFromRight == -1) { |
| 22 | break; |
| 23 | } |
| 24 | |
| 25 | if (wildcardPosFromRight == 0) { |
| 26 | return true; |
| 27 | } |
| 28 | |
| 29 | // Eat all we can and go back as far as we have to |
| 30 | for (int j = -1; j <= candidatePosFromRight; j++) { |
| 31 | if (wildcardMatch(candidate, wildcard, candidatePosFromRight: j, wildcardPosFromRight: wildcardPosFromRight - 1)) { |
| 32 | return true; |
| 33 | } |
| 34 | } |
| 35 | return false; |
| 36 | |
| 37 | case L'?': |
| 38 | if (candidatePosFromRight == -1) { |
| 39 | return false; |
| 40 | } |
| 41 | |
| 42 | candidatePosFromRight--; |
| 43 | break; |
| 44 | |
| 45 | default: |
| 46 | if (candidatePosFromRight == -1) { |
| 47 | return false; |
| 48 | } |
| 49 | |
| 50 | const auto candidateCh = candidate.at(n: candidatePosFromRight).unicode(); |
| 51 | if (candidateCh == ch) { |
| 52 | candidatePosFromRight--; |
| 53 | } else { |
| 54 | return false; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | return candidatePosFromRight == -1; |
| 59 | } |
| 60 | |
| 61 | } // unnamed namespace |
| 62 | |
| 63 | bool WildcardMatcher::exactMatch(QStringView candidate, QStringView wildcard) |
| 64 | { |
| 65 | return ::wildcardMatch(candidate, wildcard, candidatePosFromRight: candidate.length() - 1, wildcardPosFromRight: wildcard.length() - 1); |
| 66 | } |
| 67 | |