#ifndef CORE_ARRAYLIST_H #define CORE_ARRAYLIST_H #include "utils/ArrayString.h" namespace Core { template class ArrayList final { static_assert(N > 0, "ArrayList size must be positive"); struct alignas(T) Aligned { char data[sizeof(T)]; }; Aligned data[static_cast(N)]; int length; public: ArrayList() : length(0) { } ArrayList(const ArrayList& other) : ArrayList() { copy(other); } ArrayList(ArrayList&& other) : ArrayList() { move(Core::move(other)); other.clear(); } ~ArrayList() { clear(); } ArrayList& operator=(const ArrayList& other) { if(&other != this) { clear(); copy(other); } return *this; } ArrayList& operator=(ArrayList&& other) { if(&other != this) { clear(); move(Core::move(other)); other.clear(); } return *this; } T* begin() { return reinterpret_cast(data); } T* end() { return begin() + length; } const T* begin() const { return reinterpret_cast(data); } const T* end() const { return begin() + length; } // returns a nullptr on error template check_return T* add(Args&&... args) { if(length >= N) { return nullptr; } return new(begin() + length++) T(Core::forward(args)...); } T& operator[](int index) { return begin()[index]; } const T& operator[](int index) const { return begin()[index]; } int getLength() const { return length; } void clear() { for(int i = 0; i < length; i++) { begin()[i].~T(); } length = 0; } // returns true on error check_return bool removeBySwap(int index) { if(index < 0 || index >= length) { return true; } length--; if(index != length) { begin()[index] = Core::move(begin()[length]); } begin()[length].~T(); return false; } // returns true on error template check_return bool toString(ArrayString& s) const { if(s.append("[")) { return true; } for(int i = 0; i < length - 1; i++) { if(s.append(begin()[i]) || s.append(", ")) { return true; } } if(length > 0 && s.append(begin()[length - 1])) { return true; } return s.append("]"); } private: void copy(const ArrayList& other) { for(int i = 0; i < other.length; i++) { (void)add(other[i]); } } void move(ArrayList&& other) { for(int i = 0; i < other.length; i++) { (void)add(Core::move(other[i])); } } }; } #endif