#ifndef LIST_H #define LIST_H #include "utils/StringBuffer.h" #include "utils/UninitializedArray.h" template class List final { UninitializedArray data; int length = 0; void copy(const List& other) { for(int i = 0; i < other.length; i++) { add(other[i]); } } void move(List&& other) { for(int i = 0; i < other.length; i++) { add(std::move(other[i])); } } public: List() = default; void clear() { for(int i = 0; i < length; i++) { data.destroy(i); } length = 0; } ~List() { clear(); } List(const List& other) : length(0) { copy(other); } List& operator=(const List& other) { if(&other != this) { clear(); copy(other); } return *this; } List(List&& other) : length(0) { move(std::move(other)); other.clear(); } List& operator=(List&& other) { if(&other != this) { clear(); move(std::move(other)); other.clear(); } return *this; } T* begin() { return data.begin(); } T* end() { return data.begin() + length; } const T* begin() const { return data.begin(); } const T* end() const { return data.begin() + length; } bool add(const T& t) { if(length >= N) { return true; } data.init(length, t); length++; return false; } bool add(T&& t) { if(length >= N) { return true; } data.init(length, std::move(t)); length++; return false; } template bool add(Args&&... args) { if(length >= N) { return true; } data.init(length, std::forward(args)...); length++; return false; } T& operator[](int index) { return data[index]; } const T& operator[](int index) const { return data[index]; } int getLength() const { return length; } template void toString(StringBuffer& s) const { s.append("["); for(int i = 0; i < length - 1; i++) { s.append(data[i]); s.append(", "); } if(length > 0) { s.append(data[length - 1]); } s.append("]"); } bool remove(int index) { if(index < 0 || index >= length) { return true; } else if(index + 1 == length) { data.destroy(index); length--; return false; } data[index] = std::move(data[length - 1]); data.destroy(length - 1); length--; return false; } }; #endif