Skip to content

Commit 140bec0

Browse files
committed
Add constructor to support cstring_view construction from a null-terminated C string and its length (avoids duplicate strlen call)
1 parent 7487df4 commit 140bec0

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

include/tuli/cstring_view.hpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ class cstring_view {
2323
"tuli::cstring_view cannot be constructed from nullptr");
2424
}
2525

26+
constexpr cstring_view(null_terminated_t, const char* s, std::size_t len)
27+
: m_sv{s, len} {
28+
assert(m_sv.data() != nullptr &&
29+
"tuli::cstring_view cannot be constructed from nullptr");
30+
}
31+
2632
constexpr cstring_view(null_terminated_t, std::string_view sv) noexcept
2733
: m_sv{sv.data() ? sv : ""} {}
2834

tests/cstring_view.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,17 @@ TEST(CStringViewTest, FromCString) {
3030
static_assert(csv == std::string_view{s});
3131
}
3232

33+
TEST(CStringViewTest, FromNullTerminatedCStringAndLen) {
34+
constexpr auto s{"Hello, World!"};
35+
constexpr auto len{tests::strlen(s)};
36+
constexpr tuli::cstring_view csv{tuli::null_terminated, s, len};
37+
38+
static_assert(csv.length() == len);
39+
static_assert(!csv.is_empty());
40+
static_assert(tests::strcmp(csv.c_str(), s));
41+
static_assert(csv == std::string_view{s});
42+
}
43+
3344
TEST(CStringViewTest, FromNullTerminatedStringView) {
3445
constexpr auto sv{"Hello, World!"sv};
3546
constexpr tuli::cstring_view csv{tuli::null_terminated, sv};

0 commit comments

Comments
 (0)