Finish vector

This commit is contained in:
Maurice Heumann 2022-12-21 21:53:18 +01:00
parent 4cd7e711f7
commit d778a3190a

View File

@ -2,7 +2,10 @@
#include "type_traits.hpp"
#include "memory.hpp"
#include "exception.hpp"
#include "finally.hpp"
namespace utils
{
template <typename T>
class vector
{
@ -75,7 +78,7 @@ public:
this->storage_ = allocate_memory_for_capacity(capacity);
this->capacity_ = capacity;
auto _ = finally([&old_mem]
auto _ = utils::finally([&old_mem]
{
free_memory(old_mem);
});
@ -84,7 +87,7 @@ public:
for (size_t i = 0; i < this->size_; ++i)
{
new(data + i) T(std::move(old_data[i]));
old_data[i]->~T();
old_data[i].~T();
}
}
@ -101,8 +104,17 @@ public:
return *data;
}
T& operator[](const size_t index)
{
return this->at(index);
}
T& at(size_t index)
const T& operator[](const size_t index) const
{
return this->at(index);
}
T& at(const size_t index)
{
if (index >= this->size_)
{
@ -112,7 +124,7 @@ public:
return this->data()[index];
}
const T& at(size_t index) const
const T& at(const size_t index) const
{
if (index >= this->size_)
{
@ -127,21 +139,21 @@ public:
auto* data = this->data();
for (size_t i = 0; i < this->size_; ++i)
{
data[i]->~T();
data[i].~T();
}
free_memory(this->storage_);
this->storage_ = nullptr;
this->capacity_ = nullptr;
this->size_ = nullptr;
this->capacity_ = 0;
this->size_ = 0;
}
size_t capacity() const
[[nodiscard]] size_t capacity() const
{
return this->capacity_;
}
size_t size() const
[[nodiscard]] size_t size() const
{
return this->size_;
}
@ -166,6 +178,26 @@ public:
return static_cast<const T*>(align_pointer(this->storage_));
}
T* begin()
{
return this->data();
}
const T* begin() const
{
return this->data();
}
T* end()
{
return this->data() + this->size_;
}
const T* end() const
{
return this->data() + this->size_;
}
private:
void* storage_{nullptr};
size_t capacity_{0};
@ -187,9 +219,10 @@ private:
static U* align_pointer(U* pointer)
{
const auto align_bits = alignof(T) - 1;
auto ptr = static_cast<intptr_t>(pointer);
auto ptr = reinterpret_cast<intptr_t>(pointer);
ptr = (ptr + align_bits) & (~align_bits);
return static_cast<U*>(ptr);
return reinterpret_cast<U*>(ptr);
}
};
}