Files
MontaukOS/kernel/src/CppLib/Vector.hpp
T
2026-04-10 23:16:02 +02:00

81 lines
1.8 KiB
C++

/*
* vector.hpp
* Kernel C++ platform: Vector library
* Copyright (c) 2025 Daniel Hammer
*/
#pragma once
#include <cstdint>
#include <Terminal/Terminal.hpp>
#include <Memory/Heap.hpp>
#include <Memory/PageFrameAllocator.hpp>
#include <Common/Panic.hpp>
#include <initializer_list>
namespace kcp
{
template<typename T>
class vector {
protected:
T* array = nullptr;
std::size_t sz = 0;
std::size_t capacity = 0;
public:
vector() = default;
vector(std::initializer_list<T> initList) {
for (auto itr = initList.begin(); itr != initList.end(); itr++) {
T item = *itr;
push_back(item);
}
}
T& operator[](std::size_t position)
{
if (position >= sz || array == nullptr) {
Panic("Vector out of bounds caught!", nullptr);
__builtin_unreachable();
}
return array[position];
}
T& at(std::int64_t position) {
return this->operator[](position);
}
size_t push_back(T value) {
size_t _sz = sz;
if (capacity < sz + 1) {
size_t newCapacity = (capacity == 0) ? 4 : (capacity * 2);
T* newArray = (T*)Memory::g_heap->Realloc(array, sizeof(T) * newCapacity);
if (newArray == nullptr) {
Panic("Vector allocation failed!", nullptr);
__builtin_unreachable();
}
array = newArray;
capacity = newCapacity;
}
array[sz++] = value;
return _sz;
}
T* get_array()
{
return array;
}
size_t size() {
return sz;
}
};
};