From 2a34be2e7b452aa623b9043b7decf83c2e367cc7 Mon Sep 17 00:00:00 2001 From: Brett Date: Mon, 24 Jun 2024 13:52:15 -0400 Subject: [PATCH] fix expanding buffer, memory allocation now accounts for 0 (default 16) --- CMakeLists.txt | 2 +- include/blt/std/memory.h | 14 ++++++++------ include/blt/std/memory_util.h | 4 +++- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4adaffd..6219477 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.20) 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_TARGET BLT) diff --git a/include/blt/std/memory.h b/include/blt/std/memory.h index 0915123..b13adea 100644 --- a/include/blt/std/memory.h +++ b/include/blt/std/memory.h @@ -269,7 +269,7 @@ namespace blt using const_reverse_iterator = std::reverse_iterator; private: T* buffer_ = nullptr; - size_t size_; + size_t size_ = 0; public: constexpr expanding_buffer(): buffer_(nullptr), size_(0) {} @@ -465,23 +465,25 @@ namespace blt private: void expand(blt::size_t size) { - size = std::max(this->size(), size); - T* new_buffer = new T[blt::mem::next_byte_allocation(size)]; + size = std::max(size_, size); + size = blt::mem::next_byte_allocation(size); + T* new_buffer = new T[size]; if constexpr (std::is_trivially_copyable_v) { - std::memcpy(new_buffer, buffer_, size * sizeof(T)); + std::memcpy(new_buffer, buffer_, size_ * sizeof(T)); } else { if constexpr (std::is_copy_constructible_v && !std::is_move_constructible_v) { - for (size_t i = 0; i < size; i++) + for (size_t i = 0; i < size_; i++) new_buffer[i] = T(buffer_[i]); } else - for (size_t i = 0; i < size; i++) + for (size_t i = 0; i < size_; i++) new_buffer[i] = std::move(buffer_[i]); } delete[] buffer_; buffer_ = new_buffer; + size_ = size; } inline void delete_this(T* buffer, blt::size_t) diff --git a/include/blt/std/memory_util.h b/include/blt/std/memory_util.h index bfe8b06..cf61546 100644 --- a/include/blt/std/memory_util.h +++ b/include/blt/std/memory_util.h @@ -113,8 +113,10 @@ namespace blt::mem 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) return prev_size * 2; return prev_size + default_allocation_block;