From 3e29d04bc564f89c94d1e3375de54870e03df7b1 Mon Sep 17 00:00:00 2001 From: Aqua-sama Date: Tue, 14 Apr 2020 16:39:34 +0300 Subject: Add tests for MatcherRule and RegexRule --- staging/adblock/rule.h | 92 +++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 73 insertions(+), 19 deletions(-) (limited to 'staging/adblock/rule.h') diff --git a/staging/adblock/rule.h b/staging/adblock/rule.h index a9a9592..03970dc 100644 --- a/staging/adblock/rule.h +++ b/staging/adblock/rule.h @@ -6,48 +6,102 @@ * SPDX-License-Identifier: GPL-3.0 */ -#include "options.h" -#include -#include - #ifndef SMOLBOTE_ADBLOCK_RULE_H #define SMOLBOTE_ADBLOCK_RULE_H -class QStringMatcher; -class QRegularExpression; +#include "options.h" +#include +#include +#include +#include namespace AdblockPlus { class Rule { public: - // virtual bool hasMatch(const QString &url) const = 0; + virtual ~Rule() = default; + virtual bool hasMatch(const QStringRef &) const = 0; + bool shouldRedirect() const + { + return options.redirect; + } + bool shouldBlock() const + { + return !options.exception; + } + +protected: + Rule(const Options &opt) + : options(opt) + { + } + const Options options; }; class MatcherRule : public Rule { - Q_DISABLE_COPY(MatcherRule) - public: - MatcherRule(const QString &rule, const Options &opt); - ~MatcherRule(); + enum MatchPosition { + UrlStartsWith, + UrlEndsWith, + UrlContains + }; + + MatcherRule(const QString &pattern, const Options &opt, const MatchPosition pos = UrlContains) + : Rule(opt) + , position(pos) + , matcher(pattern, opt.matchcase ? Qt::CaseSensitive : Qt::CaseInsensitive) + , patternLength(pattern.length()) + { + } + explicit MatcherRule(const MatcherRule &) = delete; + MatcherRule &operator=(const MatcherRule &) = delete; + + ~MatcherRule() = default; + bool hasMatch(const QStringRef &url) const override + { + const auto index = matcher.indexIn(url); + + switch(position) { + case UrlStartsWith: + return (index == 0); + case UrlEndsWith: + return (index == url.length() - patternLength); + case UrlContains: + return (index != -1); + } + } private: - Options options; - QStringMatcher *matcher; + const MatchPosition position; + const QStringMatcher matcher; + const int patternLength; }; class RegexRule : public Rule { - Q_DISABLE_COPY(RegexRule) - public: - RegexRule(const QString &rule, const Options &opt); - ~RegexRule(); + RegexRule(const QString &rule, const Options &opt) + : Rule(opt) + , regex(rule) + { + if(!opt.matchcase) { + regex.setPatternOptions(QRegularExpression::CaseInsensitiveOption); + } + } + explicit RegexRule(const RegexRule &) = delete; + RegexRule &operator=(const RegexRule &) = delete; + + ~RegexRule() = default; + bool hasMatch(const QStringRef &url) const override + { + const auto match = regex.match(url); + return match.hasMatch(); + } private: - Options options; - QRegularExpression *regex; + QRegularExpression regex; }; } // namespace AdblockPlus -- cgit v1.2.1