From be4a61cc8040ffc1f86bd582a7de5d67397cdb16 Mon Sep 17 00:00:00 2001 From: Brett Date: Tue, 5 Mar 2024 13:20:17 -0500 Subject: [PATCH] allocator fix --- include/blt/std/allocator.h | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/include/blt/std/allocator.h b/include/blt/std/allocator.h index 0852f00..f4c227e 100644 --- a/include/blt/std/allocator.h +++ b/include/blt/std/allocator.h @@ -423,34 +423,38 @@ namespace blt struct block { blt::u8* buffer = nullptr; - blt::size_t offset = 0; + blt::u8* offset = nullptr; blt::size_t allocated_objects = 0; blt::size_t deallocated_objects = 0; + + explicit block(blt::u8* buffer): buffer(buffer), offset(buffer) + {} }; + ALLOC allocator; std::vector> blocks; blt::size_t size_; void expand() { - blocks.push_back({static_cast(allocator.allocate(size_)), 0}); + auto ptr = static_cast(allocator.allocate(size_)); + blocks.push_back(block{ptr}); } template T* allocate_back() { auto& back = blocks.back(); - size_t remaining_bytes = size_ - back.offset; - auto void_ptr = reinterpret_cast(&back.buffer[back.offset]); - auto new_ptr = static_cast(std::align(alignof(T), sizeof(T), void_ptr, remaining_bytes)); - if (new_ptr == nullptr) - expand(); - else + size_t remaining_bytes = size_ - static_cast(back.offset - back.buffer); + auto pointer = static_cast(back.offset); + const auto aligned_address = std::align(alignof(T), sizeof(T), pointer, remaining_bytes); + if (aligned_address != nullptr) { - back.offset += (back.buffer - new_ptr + sizeof(T)); + back.offset = static_cast(aligned_address) + sizeof(T); back.allocated_objects++; } - return reinterpret_cast(new_ptr); + + return static_cast(aligned_address); } public: @@ -465,13 +469,9 @@ namespace blt template [[nodiscard]] T* allocate() { - if (blocks.back().offset + sizeof(T) > size_) - expand(); if (auto ptr = allocate_back(); ptr == nullptr) - { - BLT_INFO("Not enough space for me"); expand(); - } else + else return ptr; if (auto ptr = allocate_back(); ptr == nullptr) throw std::bad_alloc(); @@ -487,7 +487,7 @@ namespace blt for (auto e : blt::enumerate(blocks)) { auto& block = e.second; - if (ptr >= block.buffer && ptr <= &block.buffer[block.offset]) + if (ptr >= block.buffer && ptr <= block.offset) { block.deallocated_objects++; if (block.deallocated_objects == block.allocated_objects)