Add iterators to Buffer

This commit is contained in:
Matias Fontanini
2016-06-16 07:46:55 -07:00
parent 8db1df0998
commit e1c2ee34fe
3 changed files with 41 additions and 7 deletions

View File

@@ -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
*/

View File

@@ -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<char>(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<int>(value) << dec;
}
}
return output;

View File

@@ -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);