summaryrefslogtreecommitdiff
path: root/lib/utils/mu-regex.hh
blob: 45ad20db81bc3fe15b1a0589982c0246d4e36879 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/*
** Copyright (C) 2022-2023 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
**
** 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 3, 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 MU_REGEX_HH__
#define MU_REGEX_HH__

#include <glib.h>
#
#include <utils/mu-result.hh>
#include <utils/mu-utils.hh>

namespace Mu {
/**
 * RAII wrapper around a GRegex which in itself is a wrapper around PCRE. We use
 * PCRE rather than std::regex because it is much faster.
 */
struct Regex {
#if !GLIB_CHECK_VERSION(2,74,0) /* backward compat */
#define G_REGEX_DEFAULT	      (static_cast<GRegexCompileFlags>(0))
#define G_REGEX_MATCH_DEFAULT (static_cast<GRegexMatchFlags>(0))
#endif
	/**
	 * Trivial constructor
	 *
	 * @return
	 */
	Regex() noexcept: rx_{}  {}

	/**
	 * Construct a new Regex object
	 *
	 * @param ptrn PRRE regular expression pattern
	 * @param cflags compile flags
	 * @param mflags match flags
	 *
	 * @return a Regex object or an error.
	 */
	static Result<Regex> make(const std::string& ptrn,
				  GRegexCompileFlags cflags = G_REGEX_DEFAULT,
				  GRegexMatchFlags mflags = G_REGEX_MATCH_DEFAULT) noexcept try {
		return Regex(ptrn.c_str(), cflags, mflags);
	} catch (const Error& err) {
		return Err(err);
	}


	/**
	 * Copy CTOR
	 *
	 * @param other some other Regex
	 */
	Regex(const Regex& other) noexcept: rx_{}  { *this = other; }

	/**
	 * Move CTOR
	 *
	 * @param other some other Regex
	 */
	Regex(Regex&& other) noexcept: rx_{} { *this = std::move(other); }


	/**
	 * DTOR
	 */
	~Regex() noexcept { g_clear_pointer(&rx_, g_regex_unref); }

	/**
	 * Cast to the underlying GRegex*
	 *
	 * @return a GRegex*
	 */
	operator const GRegex*() const noexcept { return rx_; }

	/**
	 * Doe this object contain a valid GRegex*?
	 *
	 * @return true or false
	 */
	operator bool() const noexcept { return !!rx_; }

	/**
	 * operator=
	 *
	 * @param other copy some other object to this one
	 *
	 * @return *this
	 */
	Regex& operator=(const Regex& other) noexcept {
		if (this != &other) {
			g_clear_pointer(&rx_, g_regex_unref);
			if (other.rx_)
				rx_ = g_regex_ref(other.rx_);
		}
		return *this;
	}

	/**
	 * operator=
	 *
	 * @param other move some other object to this one
	 *
	 * @return *this
	 */
	Regex& operator=(Regex&& other) noexcept {
		if (this != &other) {
			g_clear_pointer(&rx_, g_regex_unref);
			rx_ = other.rx_;
			other.rx_ = nullptr;
		}
		return *this;
	}

	/**
	 * Does this regexp match the given string? An unset Regex matches
	 * nothing.
	 *
	 * @param str string to test
	 * @param mflags match flags
	 *
	 * @return true or false
	 */
	bool matches(const std::string& str,
		     GRegexMatchFlags mflags=G_REGEX_MATCH_DEFAULT) const noexcept {
		if (!rx_)
			return false;
		else
			return g_regex_match(rx_, str.c_str(), mflags, nullptr);
		// strangely, valgrind reports some memory error related to
		// the str.c_str(). It *seems* like a false alarm.
	}

	/**
	 * Replace all occurrences of @this regexp in some string with a
	 * replacement string
	 *
	 * @param str some string
	 * @param repl replacement string
	 *
	 * @return string or error
	 */
	Result<std::string> replace(const std::string& str, const std::string& repl) const {
		GError *gerr{};

		if (!rx_)
			return Err(Error::Code::InvalidArgument, "missing regexp");
		else if (auto&& s{g_regex_replace(rx_, str.c_str(), str.length(), 0,
					     repl.c_str(), G_REGEX_MATCH_DEFAULT, &gerr)}; !s)
			return Err(Error::Code::InvalidArgument, &gerr, "error in Regex::replace");
		else
			return Ok(to_string_gchar(std::move(s)));
	}

	const GRegex* g_regex() const { return rx_; }

private:
	Regex(const char *ptrn, GRegexCompileFlags cflags, GRegexMatchFlags mflags) {
		GError *err{};
		if (rx_ = g_regex_new(ptrn, cflags, mflags, &err); !rx_)
			throw Error{Error::Code::InvalidArgument, &err,
				"invalid regexp: '{}'", ptrn};
	}

	GRegex *rx_{};
};

static inline std::string format_as(const Regex& rx) {
	if (auto&& grx{rx.g_regex()}; !grx)
		return "//";
	else
		return mu_format("/{}/", g_regex_get_pattern(grx));

}


} // namespace Mu


#endif /* MU_REGEX_HH__ */