StringFilter.hxx 2.46 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2019 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifndef MPD_STRING_FILTER_HXX
#define MPD_STRING_FILTER_HXX

#include "lib/icu/Compare.hxx"
24
#include "util/Compiler.h"
25
#include "config.h"
26

27 28 29 30
#ifdef HAVE_PCRE
#include "lib/pcre/UniqueRegex.hxx"
#endif

31
#include <string>
32
#include <memory>
33 34 35 36 37 38 39 40 41

class StringFilter {
	std::string value;

	/**
	 * This value is only set if case folding is enabled.
	 */
	IcuCompare fold_case;

42 43 44 45
#ifdef HAVE_PCRE
	std::shared_ptr<UniqueRegex> regex;
#endif

46 47 48 49 50
	/**
	 * Search for substrings instead of matching the whole string?
	 */
	bool substring;

51 52
	bool negated;

53 54
public:
	template<typename V>
55
	StringFilter(V &&_value, bool _fold_case, bool _substring, bool _negated)
56 57 58
		:value(std::forward<V>(_value)),
		 fold_case(_fold_case
			   ? IcuCompare(value.c_str())
59
			   : IcuCompare()),
60
		 substring(_substring), negated(_negated) {}
61 62 63 64 65

	bool empty() const noexcept {
		return value.empty();
	}

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	bool IsRegex() const noexcept {
#ifdef HAVE_PCRE
		return !!regex;
#else
		return false;
#endif
	}

#ifdef HAVE_PCRE
	template<typename R>
	void SetRegex(R &&_regex) noexcept {
		regex = std::forward<R>(_regex);
	}
#endif

81 82 83 84 85 86 87 88
	const auto &GetValue() const noexcept {
		return value;
	}

	bool GetFoldCase() const noexcept {
		return fold_case;
	}

89 90 91 92 93 94 95 96 97
	bool IsNegated() const noexcept {
		return negated;
	}

	void ToggleNegated() noexcept {
		negated = !negated;
	}

	const char *GetOperator() const noexcept {
98 99
		return IsRegex()
			? (negated ? "!~" : "=~")
100 101 102
			: (substring
			   ? (negated ? "!contains" : "contains")
			   : (negated ? "!=" : "=="));
103 104
	}

105 106
	gcc_pure
	bool Match(const char *s) const noexcept;
107

108 109 110
	/**
	 * Like Match(), but ignore the "negated" flag.
	 */
111 112
	gcc_pure
	bool MatchWithoutNegation(const char *s) const noexcept;
113 114 115
};

#endif