Skip to content

Commit 13cc1e0

Browse files
committed
Problem: Sending string literals is awkward
Solution: A function str_buffer specifically for creating buffers for null terminated string literals.
1 parent 3b1038d commit 13cc1e0

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

tests/buffer.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,20 @@ TEST_CASE("const_buffer creation string_view", "[buffer]")
236236
}
237237
#endif
238238

239+
TEST_CASE("const_buffer creation with str_buffer", "[buffer]")
240+
{
241+
const wchar_t wd[10] = {};
242+
zmq::const_buffer b = zmq::str_buffer(wd);
243+
CHECK(b.size() == 9 * sizeof(wchar_t));
244+
CHECK(b.data() == static_cast<const wchar_t*>(wd));
245+
246+
zmq::const_buffer b2_null = zmq::buffer("hello");
247+
zmq::const_buffer b2 = zmq::str_buffer("hello");
248+
CHECK(b2_null.size() == 6);
249+
CHECK(b2.size() == 5);
250+
CHECK(std::string(static_cast<const char*>(b2.data()), b2.size()) == "hello");
251+
}
252+
239253
TEST_CASE("buffer of structs", "[buffer]")
240254
{
241255
struct some_pod

zmq.hpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1110,6 +1110,19 @@ const_buffer buffer(std::basic_string_view<T, Traits> data, size_t n_bytes) noex
11101110
}
11111111
#endif
11121112

1113+
// Buffer for a string literal (null terminated)
1114+
// where the buffer size excludes the terminating character.
1115+
// Equivalent to zmq::buffer(std::string_view("...")).
1116+
template<class Char, size_t N>
1117+
const_buffer str_buffer(const Char (&data)[N]) noexcept
1118+
{
1119+
static_assert(detail::is_pod_like<Char>::value, "Char must be POD");
1120+
static_assert(N > 0, "N > 0");
1121+
assert(data[N - 1] == Char{0});
1122+
return const_buffer(N == 1 ? nullptr : static_cast<const Char*>(data),
1123+
(N - 1) * sizeof(Char));
1124+
}
1125+
11131126
#endif // ZMQ_CPP11
11141127

11151128
namespace detail

0 commit comments

Comments
 (0)