From 88ccba3deeb230113cc7b374fe602a32187dc272 Mon Sep 17 00:00:00 2001 From: Oskari Alaranta Date: Sat, 21 Feb 2026 03:54:08 +0200 Subject: [PATCH] BAN: Add reallocator and make Vector use it --- BAN/include/BAN/New.h | 2 ++ BAN/include/BAN/Vector.h | 45 ++++++++++++++++++++++++++++++++-------- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/BAN/include/BAN/New.h b/BAN/include/BAN/New.h index 3602fb3..5773bf3 100644 --- a/BAN/include/BAN/New.h +++ b/BAN/include/BAN/New.h @@ -10,9 +10,11 @@ namespace BAN { #if defined(__is_kernel) static constexpr void*(&allocator)(size_t) = kmalloc; + static constexpr void*(&reallocator)(void*, size_t) = nullptr; static constexpr void(&deallocator)(void*) = kfree; #else static constexpr void*(&allocator)(size_t) = malloc; + static constexpr void*(&reallocator)(void*, size_t) = realloc; static constexpr void(&deallocator)(void*) = free; #endif } diff --git a/BAN/include/BAN/Vector.h b/BAN/include/BAN/Vector.h index 7e90c0f..18f0b77 100644 --- a/BAN/include/BAN/Vector.h +++ b/BAN/include/BAN/Vector.h @@ -381,19 +381,46 @@ namespace BAN template ErrorOr Vector::ensure_capacity(size_type size) { + static_assert(alignof(T) <= alignof(max_align_t), "over aligned types not supported"); + if (m_capacity >= size) return {}; - size_type new_cap = BAN::Math::max(size, m_capacity * 2); - T* new_data = (T*)BAN::allocator(new_cap * sizeof(T)); - if (new_data == nullptr) - return Error::from_errno(ENOMEM); - for (size_type i = 0; i < m_size; i++) + + const size_type new_cap = BAN::Math::max(size, m_capacity * 2); + + if constexpr (BAN::is_trivially_copyable_v) { - new (new_data + i) T(move(m_data[i])); - m_data[i].~T(); + if constexpr (BAN::reallocator) + { + auto* new_data = static_cast(BAN::reallocator(m_data, new_cap * sizeof(T))); + if (new_data == nullptr) + return Error::from_errno(ENOMEM); + m_data = new_data; + } + else + { + auto* new_data = static_cast(BAN::allocator(new_cap * sizeof(T))); + if (new_data == nullptr) + return Error::from_errno(ENOMEM); + memcpy(new_data, m_data, m_size * sizeof(T)); + BAN::deallocator(m_data); + m_data = new_data; + } } - BAN::deallocator(m_data); - m_data = new_data; + else + { + auto* new_data = static_cast(BAN::allocator(new_cap * sizeof(T))); + if (new_data == nullptr) + return Error::from_errno(ENOMEM); + for (size_type i = 0; i < m_size; i++) + { + new (new_data + i) T(move(m_data[i])); + m_data[i].~T(); + } + BAN::deallocator(m_data); + m_data = new_data; + } + m_capacity = new_cap; return {}; }