From dc0f6dd12e26b428fdc74f159d66182dd4b0b1e3 Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Wed, 6 Mar 2024 13:14:11 -0500 Subject: [PATCH] cpp-common/bt2c: add `CStringView::startsWith` Change-Id: I4a39561085850c06adc1f6e36466fba9a2e6dfa0 Signed-off-by: Simon Marchi Reviewed-on: https://review.lttng.org/c/babeltrace/+/12011 Tested-by: jenkins Reviewed-by: Philippe Proulx --- src/cpp-common/bt2c/c-string-view.hpp | 7 +++++++ tests/cpp-common/test-c-string-view.cpp | 17 ++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/cpp-common/bt2c/c-string-view.hpp b/src/cpp-common/bt2c/c-string-view.hpp index 3dca0299..0437cd65 100644 --- a/src/cpp-common/bt2c/c-string-view.hpp +++ b/src/cpp-common/bt2c/c-string-view.hpp @@ -176,6 +176,13 @@ public: return _mStr[i]; } + bool startsWith(const bt2c::CStringView prefix) const noexcept + { + BT_ASSERT_DBG(_mStr); + BT_ASSERT_DBG(prefix); + return std::strncmp(_mStr, prefix, prefix.len()) == 0; + } + private: const char *_mStr = nullptr; }; diff --git a/tests/cpp-common/test-c-string-view.cpp b/tests/cpp-common/test-c-string-view.cpp index 97eaf6dc..70e624d2 100644 --- a/tests/cpp-common/test-c-string-view.cpp +++ b/tests/cpp-common/test-c-string-view.cpp @@ -74,11 +74,26 @@ void testEquality() testNe(foo1, bt2c::CStringView {bar}); } +void testStartsWith() +{ + ok(bt2c::CStringView {"Moutarde choux"}.startsWith("Moutarde"), + "\"Moutarde Choux\" starts with \"Moutarde\""); + ok(!bt2c::CStringView {"Moutarde choux"}.startsWith("Choux"), + "\"Moutarde Choux\" does not start with \"Choux\""); + ok(bt2c::CStringView {"Moutarde choux"}.startsWith(""), "\"Moutarde Choux\" starts with \"\""); + ok(bt2c::CStringView {"Moutarde choux"}.startsWith("Moutarde choux"), + "\"Moutarde Choux\" starts with \"Moutarde choux\""); + ok(!bt2c::CStringView {"Moutarde"}.startsWith("Moutarde choux"), + "\"Moutarde\" does not start with \"Moutarde choux\""); + ok(bt2c::CStringView {""}.startsWith(""), "\"\" starts with \"\""); +} + } /* namespace */ int main() { - plan_tests(10); + plan_tests(16); testEquality(); + testStartsWith(); return exit_status(); } -- 2.34.1