From 617ebd0bd744613201aa3e19d217da89a735f3e0 Mon Sep 17 00:00:00 2001 From: j2-pelczar <jakub2.pelczar@live.uwe.ac.uk> Date: Wed, 27 Nov 2024 21:38:32 +0000 Subject: [PATCH] Upload New File --- worksheet_two/task_3/bump_allocator.hpp | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 worksheet_two/task_3/bump_allocator.hpp diff --git a/worksheet_two/task_3/bump_allocator.hpp b/worksheet_two/task_3/bump_allocator.hpp new file mode 100644 index 0000000..2c87663 --- /dev/null +++ b/worksheet_two/task_3/bump_allocator.hpp @@ -0,0 +1,51 @@ +#ifndef BUMP_ALLOCATOR_HPP +#define BUMP_ALLOCATOR_HPP + +#include <cstddef> +#include <iostream> + +class BumpAllocator { +private: + char* memory; + std::size_t size; + char* current_up; // Pointer for bumping up + char* current_down; // Pointer for bumping down + +public: + BumpAllocator(std::size_t totalSize) + : size(totalSize), memory(new char[totalSize]) { + current_up = memory; + current_down = memory + size; + } + + ~BumpAllocator() { + delete[] memory; + } + + // Allocate by bumping up + void* allocateUp(std::size_t allocSize) { + if (current_up + allocSize > current_down) { + throw std::bad_alloc(); + } + void* result = current_up; + current_up += allocSize; + return result; + } + + // Allocate by bumping down + void* allocateDown(std::size_t allocSize) { + if (current_down - allocSize < current_up) { + throw std::bad_alloc(); + } + current_down -= allocSize; + return current_down; + } + + // Reset allocator + void reset() { + current_up = memory; + current_down = memory + size; + } +}; + +#endif -- GitLab