123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- #ifndef LIST_H
- #define LIST_H
- #include <utility>
- #include "utils/StringBuffer.h"
- template<typename T, int N>
- class List final {
- char data[sizeof (T) * N];
- 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++) {
- (*this)[i].~T();
- }
- 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 reinterpret_cast<T*> (data);
- }
- T* end() {
- return reinterpret_cast<T*> (data) + length;
- }
- const T* begin() const {
- return reinterpret_cast<const T*> (data);
- }
- const T* end() const {
- return reinterpret_cast<const T*> (data) + length;
- }
- bool add(const T& t) {
- if(length >= N) {
- return true;
- }
- new (end()) T(t);
- length++;
- return false;
- }
- bool add(T&& t) {
- if(length >= N) {
- return true;
- }
- new (end()) T(std::move(t));
- length++;
- return false;
- }
- template<typename... Args>
- bool add(Args&&... args) {
- if(length >= N) {
- return true;
- }
- new (end()) T(std::forward<Args>(args)...);
- length++;
- return false;
- }
- T& operator[](int index) {
- return begin()[index];
- }
- const T& operator[](int index) const {
- return begin()[index];
- }
- int getLength() const {
- return length;
- }
- template<int L>
- void toString(StringBuffer<L>& s) const {
- s.append("[");
- for(int i = 0; i < length - 1; i++) {
- s.append((*this)[i]);
- s.append(", ");
- }
- if(length > 0) {
- s.append((*this)[length - 1]);
- }
- s.append("]");
- }
- bool remove(int index) {
- if(index < 0 || index >= length) {
- return true;
- } else if(index + 1 == length) {
- (*this)[index].~T();
- length--;
- return false;
- }
- (*this)[index] = std::move((*this)[length - 1]);
- (*this)[length - 1].~T();
- length--;
- return false;
- }
- };
- #endif
|