buffer: Refactor

This commit is contained in:
Tatsuhiro Tsujikawa 2015-02-05 22:58:37 +09:00
parent 7baf6f781e
commit 6774fa6e07
2 changed files with 13 additions and 13 deletions

View File

@ -29,21 +29,21 @@
#include <cstring>
#include <algorithm>
#include <array>
namespace nghttp2 {
template <size_t N> struct Buffer {
Buffer() : pos(begin), last(begin) {}
Buffer() : pos(std::begin(buf)), last(pos) {}
// Returns the number of bytes to read.
size_t rleft() const { return last - pos; }
// Returns the number of bytes this buffer can store.
size_t wleft() const { return begin + N - last; }
size_t wleft() const { return std::end(buf) - last; }
// Writes up to min(wleft(), |count|) bytes from buffer pointed by
// |buf|. Returns number of bytes written.
size_t write(const void *buf, size_t count) {
// |src|. Returns number of bytes written.
size_t write(const void *src, size_t count) {
count = std::min(count, wleft());
memcpy(last, buf, count);
last += count;
last = std::copy_n(static_cast<const uint8_t *>(src), count, last);
return count;
}
size_t write(size_t count) {
@ -57,8 +57,8 @@ template <size_t N> struct Buffer {
pos += count;
return count;
}
void reset() { pos = last = begin; }
uint8_t begin[N];
void reset() { pos = last = std::begin(buf); }
std::array<uint8_t, N> buf;
uint8_t *pos, *last;
};

View File

@ -45,13 +45,13 @@ void test_buffer_write(void) {
CU_ASSERT(3 == b.rleft());
CU_ASSERT(13 == b.wleft());
CU_ASSERT(0 == b.pos - b.begin);
CU_ASSERT(0 == b.pos - std::begin(b.buf));
b.drain(3);
CU_ASSERT(0 == b.rleft());
CU_ASSERT(13 == b.wleft());
CU_ASSERT(3 == b.pos - b.begin);
CU_ASSERT(3 == b.pos - std::begin(b.buf));
auto n = b.write("0123456789ABCDEF", 16);
@ -59,20 +59,20 @@ void test_buffer_write(void) {
CU_ASSERT(13 == b.rleft());
CU_ASSERT(0 == b.wleft());
CU_ASSERT(3 == b.pos - b.begin);
CU_ASSERT(3 == b.pos - std::begin(b.buf));
CU_ASSERT(0 == memcmp(b.pos, "0123456789ABC", 13));
b.reset();
CU_ASSERT(0 == b.rleft());
CU_ASSERT(0 == b.wleft());
CU_ASSERT(0 == b.pos - b.begin);
CU_ASSERT(0 == b.pos - std::begin(b.buf));
b.write(5);
CU_ASSERT(5 == b.rleft());
CU_ASSERT(11 == b.wleft());
CU_ASSERT(0 == b.pos - b.begin);
CU_ASSERT(0 == b.pos - std::begin(b.buf));
}
} // namespace nghttp2