From: Simon Marchi Date: Fri, 31 May 2024 19:40:15 +0000 (-0400) Subject: cpp-common/bt2c: add `Regex` X-Git-Url: http://drtracing.org/?a=commitdiff_plain;h=6f3c472e6b793025065c48f9576066dbb40a490d;p=babeltrace.git cpp-common/bt2c: add `Regex` Add `Regex`, a class wrapping some features of `GRegex` (from glib). The constructor aborts if the regex pattern fails to compile. There is a single `match()` method that returns whether or not the given string matches the regex. Change-Id: Ia4cb1542efa91fcf3849d82d047c871d9bf2dbd2 Signed-off-by: Simon Marchi Reviewed-on: https://review.lttng.org/c/babeltrace/+/12837 Tested-by: jenkins Reviewed-by: Philippe Proulx --- diff --git a/src/Makefile.am b/src/Makefile.am index 4442a1f8..a8b4e2af 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -173,6 +173,7 @@ cpp_common_libcpp_common_la_SOURCES = \ cpp-common/bt2c/make-span.hpp \ cpp-common/bt2c/prio-heap.hpp \ cpp-common/bt2c/read-fixed-len-int.hpp \ + cpp-common/bt2c/regex.hpp \ cpp-common/bt2c/safe-ops.hpp \ cpp-common/bt2c/std-int.hpp \ cpp-common/bt2c/text-loc.cpp \ diff --git a/src/cpp-common/bt2c/regex.hpp b/src/cpp-common/bt2c/regex.hpp new file mode 100644 index 00000000..350cea75 --- /dev/null +++ b/src/cpp-common/bt2c/regex.hpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 EfficiOS Inc. + * + * SPDX-License-Identifier: MIT + */ + +#ifndef BABELTRACE_CPP_COMMON_BT2C_REGEX_HPP +#define BABELTRACE_CPP_COMMON_BT2C_REGEX_HPP + +#include + +#include "cpp-common/bt2c/logging.hpp" + +namespace bt2c { + +class Regex final +{ +public: + explicit Regex(const char * const pattern) noexcept + { + GError *error = nullptr; + + _mRegex = g_regex_new(pattern, G_REGEX_OPTIMIZE, static_cast(0), &error); + + if (!_mRegex) { + BT_CPPLOGF_SPEC((bt2c::Logger {"BT2C", "REGEX", bt2c::Logger::Level::Fatal}), + "g_regex_new() failed: {}", error->message); + bt_common_abort(); + } + } + + Regex(const Regex&) = delete; + Regex& operator=(const Regex&) = delete; + + ~Regex() + { + g_regex_unref(_mRegex); + } + + bool match(const bt2s::string_view str) const noexcept + { + return g_regex_match_full(_mRegex, str.data(), str.size(), 0, + static_cast(0), nullptr, nullptr); + } + +private: + GRegex *_mRegex; +}; + +} /* namespace bt2c */ + +#endif /* BABELTRACE_CPP_COMMON_BT2C_REGEX_HPP */