cpp-common/bt2c: add `CStringView::startsWith`
[babeltrace.git] / tests / cpp-common / test-c-string-view.cpp
CommitLineData
821af099
SM
1/*
2 * SPDX-License-Identifier: GPL-2.0-only
3 *
4 * Copyright (C) 2024 EfficiOS, Inc.
5 */
6
7#include <string>
8
9#include "cpp-common/bt2c/c-string-view.hpp"
10
11#include "tap/tap.h"
12
13namespace {
14
15template <typename StrT>
16const char *asConstCharPtr(StrT&& val)
17{
18 return val.data();
19}
20
21const char *asConstCharPtr(const char * const val)
22{
23 return val;
24}
25
26const char *typeName(bt2c::CStringView)
27{
28 return "bt2c::CStringView";
29}
30
31const char *typeName(const char *)
32{
33 return "const char *";
34}
35
36const char *typeName(const std::string&)
37{
38 return "std::string";
39}
40
41template <typename Str1T, typename Str2T>
42void testEq(Str1T&& lhs, Str2T&& rhs)
43{
44 BT_ASSERT(asConstCharPtr(lhs) != asConstCharPtr(rhs));
45 ok(lhs == rhs, "`%s` == `%s`", typeName(lhs), typeName(rhs));
46}
47
48template <typename Str1T, typename Str2T>
49void testNe(Str1T&& lhs, Str2T&& rhs)
50{
51 BT_ASSERT(asConstCharPtr(lhs) != asConstCharPtr(rhs));
52 ok(lhs != rhs, "`%s` != `%s`", typeName(lhs), typeName(rhs));
53}
54
55void testEquality()
56{
57 const std::string foo1 = "foo", foo2 = "foo";
58 const std::string bar = "bar";
59
60 /* `CStringView` vs `CStringView` */
61 testEq(bt2c::CStringView {foo1}, bt2c::CStringView {foo2});
62 testNe(bt2c::CStringView {foo1}, bt2c::CStringView {bar});
63
64 /* `CStringView` vs `const char *` */
65 testEq(bt2c::CStringView {foo1}, foo2.c_str());
66 testNe(bt2c::CStringView {foo1}, bar.c_str());
67 testEq(foo1.c_str(), bt2c::CStringView {foo2});
68 testNe(foo1.c_str(), bt2c::CStringView {bar});
69
70 /* `StringView` vs `std::string` */
71 testEq(bt2c::CStringView {foo1}, foo2);
72 testNe(bt2c::CStringView {foo1}, bar);
73 testEq(foo1, bt2c::CStringView {foo2});
74 testNe(foo1, bt2c::CStringView {bar});
75}
76
dc0f6dd1
SM
77void testStartsWith()
78{
79 ok(bt2c::CStringView {"Moutarde choux"}.startsWith("Moutarde"),
80 "\"Moutarde Choux\" starts with \"Moutarde\"");
81 ok(!bt2c::CStringView {"Moutarde choux"}.startsWith("Choux"),
82 "\"Moutarde Choux\" does not start with \"Choux\"");
83 ok(bt2c::CStringView {"Moutarde choux"}.startsWith(""), "\"Moutarde Choux\" starts with \"\"");
84 ok(bt2c::CStringView {"Moutarde choux"}.startsWith("Moutarde choux"),
85 "\"Moutarde Choux\" starts with \"Moutarde choux\"");
86 ok(!bt2c::CStringView {"Moutarde"}.startsWith("Moutarde choux"),
87 "\"Moutarde\" does not start with \"Moutarde choux\"");
88 ok(bt2c::CStringView {""}.startsWith(""), "\"\" starts with \"\"");
89}
90
35ef83be 91} /* namespace */
821af099
SM
92
93int main()
94{
dc0f6dd1 95 plan_tests(16);
821af099 96 testEquality();
dc0f6dd1 97 testStartsWith();
821af099
SM
98 return exit_status();
99}
This page took 0.027238 seconds and 4 git commands to generate.