From e1c2ee34feab493baa5b38ca9c00fd219ecb13c3 Mon Sep 17 00:00:00 2001 From: Matias Fontanini Date: Thu, 16 Jun 2016 07:46:55 -0700 Subject: [PATCH] Add iterators to Buffer --- include/cppkafka/buffer.h | 18 ++++++++++++++++++ src/buffer.cpp | 21 ++++++++++++++------- tests/buffer_test.cpp | 9 +++++++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/include/cppkafka/buffer.h b/include/cppkafka/buffer.h index b7de88f..8cdcb28 100644 --- a/include/cppkafka/buffer.h +++ b/include/cppkafka/buffer.h @@ -49,8 +49,16 @@ namespace cppkafka { */ class Buffer { public: + /** + * The type of data this buffer points to + */ using DataType = unsigned char; + /** + * The const iterator type + */ + using const_iterator = const DataType*; + /** * Constructs an empty buffer */ @@ -94,6 +102,16 @@ public: */ size_t get_size() const; + /** + * Gets an iterator to the beginning of this buffer + */ + const_iterator begin() const; + + /** + * Gets an iterator to the end of this buffer + */ + const_iterator end() const; + /** * Checks whether this is a non empty buffer */ diff --git a/src/buffer.cpp b/src/buffer.cpp index 58a61bc..cdf59b0 100644 --- a/src/buffer.cpp +++ b/src/buffer.cpp @@ -58,8 +58,16 @@ size_t Buffer::get_size() const { return size_; } +Buffer::const_iterator Buffer::begin() const { + return data_; +} + +Buffer::const_iterator Buffer::end() const { + return data_ + size_; +} + Buffer::operator bool() const { - return data_ != nullptr; + return size_ != 0; } Buffer::operator string() const { @@ -78,17 +86,16 @@ bool Buffer::operator!=(const Buffer& rhs) const { } ostream& operator<<(ostream& output, const Buffer& rhs) { - for (size_t i = 0; i < rhs.get_size(); ++i) { - char c = static_cast(rhs.get_data()[i]); - if (c >= ' ' && c < 127) { - output << c; + for (const uint8_t value : rhs) { + if (value >= 0x20 && value < 0x7f) { + output << value; } else { output << "\\x"; - if (c < 16) { + if (value < 16) { output << '0'; } - output << hex << (int)c << dec; + output << hex << static_cast(value) << dec; } } return output; diff --git a/tests/buffer_test.cpp b/tests/buffer_test.cpp index 85540a9..ac842f0 100644 --- a/tests/buffer_test.cpp +++ b/tests/buffer_test.cpp @@ -15,6 +15,15 @@ public: }; +TEST_F(BufferTest, OperatorBool) { + string data = "Hello world!"; + Buffer buffer1(data); + Buffer buffer2; + + EXPECT_TRUE(buffer1); + EXPECT_FALSE(buffer2); +} + TEST_F(BufferTest, StringConversion) { string data = "Hello world!"; Buffer buffer(data);