diff --git a/include/osmium/memory/buffer.hpp b/include/osmium/memory/buffer.hpp index 370d01e0b..1b75b4fa5 100644 --- a/include/osmium/memory/buffer.hpp +++ b/include/osmium/memory/buffer.hpp @@ -119,6 +119,15 @@ namespace osmium { auto_grow m_auto_grow{auto_grow::no}; std::function 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: /** @@ -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"); } } diff --git a/test/t/memory/test_buffer_basics.cpp b/test/t/memory/test_buffer_basics.cpp index ffe725168..d9d174b0f 100644 --- a/test/t/memory/test_buffer_basics.cpp +++ b/test/t/memory/test_buffer_basics.cpp @@ -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); @@ -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); +} +