| 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 | |
| 13 | namespace { |
| 14 | |
| 15 | template <typename StrT> |
| 16 | const char *asConstCharPtr(StrT&& val) |
| 17 | { |
| 18 | return val.data(); |
| 19 | } |
| 20 | |
| 21 | const char *asConstCharPtr(const char * const val) |
| 22 | { |
| 23 | return val; |
| 24 | } |
| 25 | |
| 26 | const char *typeName(bt2c::CStringView) |
| 27 | { |
| 28 | return "bt2c::CStringView"; |
| 29 | } |
| 30 | |
| 31 | const char *typeName(const char *) |
| 32 | { |
| 33 | return "const char *"; |
| 34 | } |
| 35 | |
| 36 | const char *typeName(const std::string&) |
| 37 | { |
| 38 | return "std::string"; |
| 39 | } |
| 40 | |
| 41 | template <typename Str1T, typename Str2T> |
| 42 | void 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 | |
| 48 | template <typename Str1T, typename Str2T> |
| 49 | void 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 | |
| 55 | void 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 | |
| 77 | } // namespace |
| 78 | |
| 79 | int main() |
| 80 | { |
| 81 | plan_tests(10); |
| 82 | testEquality(); |
| 83 | return exit_status(); |
| 84 | } |