diff --git a/sequential/vector.hpp b/sequential/vector.hpp index 688b1c4..1ea3618 100644 --- a/sequential/vector.hpp +++ b/sequential/vector.hpp @@ -7,28 +7,65 @@ class Vector { private: T * data; + std::size_t byteSize; + std::size_t reserveSize; std::size_t size; -public: - void Resize(std::size_t const newSize) + void Allocate(std::size_t const allocationSize) { - if(newSize == 0ul) + if(allocationSize == 0ul) { std::free(data); data = nullptr; + byteSize = 0ul; + reserveSize = 0ul; return; } - void * result = std::realloc(data, newSize * sizeof(T)); + std::size_t newByteSize = allocationSize * sizeof(T); + newByteSize += newByteSize % 32ul; // Allocate in blocks of 32 bytes + + if(newByteSize <= byteSize) + { + reserveSize = allocationSize; + return; + } + + void * result = std::realloc(data, newByteSize); if(result == nullptr) { throw std::runtime_error("Cannot allocate the requested size of memory."); } - size = newSize; + byteSize = newByteSize; + reserveSize = allocationSize; data = reinterpret_cast(result); } +public: + void Resize(std::size_t const newSize) + { + if (newSize > reserveSize) + { + Allocate(newSize); + size = newSize; + return; + } + + size = newSize; + } + + void Reserve(std::size_t const newReserveSize) + { + if(newReserveSize < size) + { + Allocate(size); + return; + } + + Allocate(newReserveSize); + } + T & operator[](std::size_t const index) { if(index >= size) @@ -45,6 +82,8 @@ public: Vector() : data(nullptr), - size(0U) + byteSize(0ul), + reserveSize(0ul), + size(0ul) {} }; \ No newline at end of file