cpp-common/bt2c: add `Regex`
authorSimon Marchi <simon.marchi@efficios.com>
Fri, 31 May 2024 19:40:15 +0000 (15:40 -0400)
committerSimon Marchi <simon.marchi@efficios.com>
Wed, 4 Sep 2024 19:05:14 +0000 (15:05 -0400)
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 <simon.marchi@efficios.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/12837
Tested-by: jenkins <jenkins@lttng.org>
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
src/Makefile.am
src/cpp-common/bt2c/regex.hpp [new file with mode: 0644]

index 4442a1f806753d9bb6e25267817706e0b7382e28..a8b4e2afe24f82a7883b2657fa2dc37c064e13f3 100644 (file)
@@ -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 (file)
index 0000000..350cea7
--- /dev/null
@@ -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 <glib.h>
+
+#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<GRegexMatchFlags>(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<GRegexMatchFlags>(0), nullptr, nullptr);
+    }
+
+private:
+    GRegex *_mRegex;
+};
+
+} /* namespace bt2c */
+
+#endif /* BABELTRACE_CPP_COMMON_BT2C_REGEX_HPP */
This page took 0.028866 seconds and 4 git commands to generate.