Skip to content

Commit 895a983

Browse files
committed
Allow constructing Buffers from std::vector
1 parent c58a479 commit 895a983

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

include/cppkafka/buffer.h

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,21 @@ class CPPKAFKA_API Buffer {
7777
static_assert(sizeof(T) == sizeof(DataType), "sizeof(T) != sizeof(DataType)");
7878
}
7979

80+
/**
81+
* Constructs a buffer from a vector
82+
*
83+
* \param data The vector to be used as input
84+
*/
85+
template <typename T>
86+
Buffer(const std::vector<T>& data)
87+
: data_(data.data()), size_(data.size()) {
88+
static_assert(sizeof(T) == sizeof(DataType), "sizeof(T) != sizeof(DataType)");
89+
}
90+
91+
// Don't allow construction from temporary vectors
92+
template <typename T>
93+
Buffer(std::vector<T>&& data) = delete;
94+
8095
/**
8196
* \brief Construct a buffer from a const string ref
8297
*
@@ -85,7 +100,7 @@ class CPPKAFKA_API Buffer {
85100
*/
86101
Buffer(const std::string& data);
87102

88-
// Don't allow construction from temporaries
103+
// Don't allow construction from temporary strings
89104
Buffer(std::string&&) = delete;
90105

91106
Buffer(const Buffer&) = delete;

tests/buffer_test.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ TEST_F(BufferTest, VectorConversion) {
4343
EXPECT_EQ(data, string(buffer_as_vector.begin(), buffer_as_vector.end()));
4444
}
4545

46+
TEST_F(BufferTest, VectorConstruction) {
47+
const string str_data = "Hello world!";
48+
const vector<uint8_t> data(str_data.begin(), str_data.end());
49+
Buffer buffer(data);
50+
EXPECT_EQ(str_data, buffer);
51+
}
52+
4653
TEST_F(BufferTest, Equality) {
4754
string data = "Hello world!";
4855
Buffer buffer1(data);

0 commit comments

Comments
 (0)