fix expanding buffer, memory allocation now accounts for 0 (default 16)

v1
Brett 2024-06-24 13:52:15 -04:00
parent ac163a34b9
commit 2a34be2e7b
3 changed files with 12 additions and 8 deletions

View File

@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.20) cmake_minimum_required(VERSION 3.20)
include(cmake/color.cmake) include(cmake/color.cmake)
set(BLT_VERSION 0.17.18) set(BLT_VERSION 0.17.19)
set(BLT_TEST_VERSION 0.0.1) set(BLT_TEST_VERSION 0.0.1)
set(BLT_TARGET BLT) set(BLT_TARGET BLT)

View File

@ -269,7 +269,7 @@ namespace blt
using const_reverse_iterator = std::reverse_iterator<const_iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>;
private: private:
T* buffer_ = nullptr; T* buffer_ = nullptr;
size_t size_; size_t size_ = 0;
public: public:
constexpr expanding_buffer(): buffer_(nullptr), size_(0) constexpr expanding_buffer(): buffer_(nullptr), size_(0)
{} {}
@ -465,23 +465,25 @@ namespace blt
private: private:
void expand(blt::size_t size) void expand(blt::size_t size)
{ {
size = std::max(this->size(), size); size = std::max(size_, size);
T* new_buffer = new T[blt::mem::next_byte_allocation(size)]; size = blt::mem::next_byte_allocation(size);
T* new_buffer = new T[size];
if constexpr (std::is_trivially_copyable_v<T>) if constexpr (std::is_trivially_copyable_v<T>)
{ {
std::memcpy(new_buffer, buffer_, size * sizeof(T)); std::memcpy(new_buffer, buffer_, size_ * sizeof(T));
} else } else
{ {
if constexpr (std::is_copy_constructible_v<T> && !std::is_move_constructible_v<T>) if constexpr (std::is_copy_constructible_v<T> && !std::is_move_constructible_v<T>)
{ {
for (size_t i = 0; i < size; i++) for (size_t i = 0; i < size_; i++)
new_buffer[i] = T(buffer_[i]); new_buffer[i] = T(buffer_[i]);
} else } else
for (size_t i = 0; i < size; i++) for (size_t i = 0; i < size_; i++)
new_buffer[i] = std::move(buffer_[i]); new_buffer[i] = std::move(buffer_[i]);
} }
delete[] buffer_; delete[] buffer_;
buffer_ = new_buffer; buffer_ = new_buffer;
size_ = size;
} }
inline void delete_this(T* buffer, blt::size_t) inline void delete_this(T* buffer, blt::size_t)

View File

@ -113,8 +113,10 @@ namespace blt::mem
return fromBytes(in, *out); return fromBytes(in, *out);
} }
inline static size_t next_byte_allocation(size_t prev_size, size_t default_allocation_block = 8192) inline static size_t next_byte_allocation(size_t prev_size, size_t default_allocation_block = 8192, size_t default_size = 16)
{ {
if (prev_size < default_size)
return default_size;
if (prev_size < default_allocation_block) if (prev_size < default_allocation_block)
return prev_size * 2; return prev_size * 2;
return prev_size + default_allocation_block; return prev_size + default_allocation_block;