Skip to content

Commit

Permalink
Use minimum size of 64 bytes for buffers.
Browse files Browse the repository at this point in the history
This avoids an infinite loop in reserve_space(). See #202.
  • Loading branch information
joto committed Mar 31, 2017
1 parent 3c82892 commit 7685449
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
15 changes: 12 additions & 3 deletions include/osmium/memory/buffer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,15 @@ namespace osmium {
auto_grow m_auto_grow{auto_grow::no};
std::function<void(Buffer&)> m_full;

static size_t calculate_capacity(size_t capacity) noexcept {
// The majority of all Nodes will fit into this size.
constexpr static const size_t min_capacity = 64;
if (capacity < min_capacity) {
return min_capacity;
}
return capacity;
}

public:

/**
Expand Down Expand Up @@ -198,13 +207,13 @@ namespace osmium {
* of the alignment.
*/
explicit Buffer(size_t capacity, auto_grow auto_grow = auto_grow::yes) :
m_memory(new unsigned char[capacity]),
m_memory(new unsigned char[calculate_capacity(capacity)]),
m_data(m_memory.get()),
m_capacity(capacity),
m_capacity(calculate_capacity(capacity)),
m_written(0),
m_committed(0),
m_auto_grow(auto_grow) {
if (capacity % align_bytes != 0) {
if (m_capacity % align_bytes != 0) {
throw std::invalid_argument("buffer capacity needs to be multiple of alignment");
}
}
Expand Down
19 changes: 17 additions & 2 deletions test/t/memory/test_buffer_basics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ TEST_CASE("Buffer basics") {

osmium::memory::Buffer invalid_buffer1;
osmium::memory::Buffer invalid_buffer2;
osmium::memory::Buffer empty_buffer1(1024);
osmium::memory::Buffer empty_buffer2(2048);
osmium::memory::Buffer empty_buffer1{1024};
osmium::memory::Buffer empty_buffer2{2048};

REQUIRE(!invalid_buffer1);
REQUIRE(!invalid_buffer2);
Expand All @@ -32,3 +32,18 @@ TEST_CASE("Buffer basics") {

}

TEST_CASE("Buffer with zero size") {
osmium::memory::Buffer buffer{0};
REQUIRE(buffer.capacity() == 64);
}

TEST_CASE("Buffer with less than minimum size") {
osmium::memory::Buffer buffer{63};
REQUIRE(buffer.capacity() == 64);
}

TEST_CASE("Buffer with minimum size") {
osmium::memory::Buffer buffer{64};
REQUIRE(buffer.capacity() == 64);
}

0 comments on commit 7685449

Please sign in to comment.