List.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #ifndef LIST_H
  2. #define LIST_H
  3. #include <utility>
  4. #include "utils/StringBuffer.h"
  5. template<typename T, int N>
  6. class List final {
  7. char data[sizeof (T) * N];
  8. int index = 0;
  9. void copy(const List& other) {
  10. for(int i = 0; i < other.index; i++) {
  11. add(other[i]);
  12. }
  13. }
  14. void move(List&& other) {
  15. for(int i = 0; i < other.index; i++) {
  16. add(std::move(other[i]));
  17. }
  18. }
  19. public:
  20. List() = default;
  21. List& clear() {
  22. for(int i = 0; i < index; i++) {
  23. (*this)[i].~T();
  24. }
  25. index = 0;
  26. return *this;
  27. }
  28. ~List() {
  29. clear();
  30. }
  31. List(const List& other) : index(0) {
  32. copy(other);
  33. }
  34. List& operator=(const List& other) {
  35. if(&other != this) {
  36. clear();
  37. copy(other);
  38. }
  39. return *this;
  40. }
  41. List(List&& other) : index(0) {
  42. move(std::move(other));
  43. other.clear();
  44. }
  45. List& operator=(List&& other) {
  46. if(&other != this) {
  47. clear();
  48. move(std::move(other));
  49. other.clear();
  50. }
  51. return *this;
  52. }
  53. T* begin() {
  54. return reinterpret_cast<T*> (data);
  55. }
  56. T* end() {
  57. return reinterpret_cast<T*> (data) + index;
  58. }
  59. const T* begin() const {
  60. return reinterpret_cast<const T*> (data);
  61. }
  62. const T* end() const {
  63. return reinterpret_cast<const T*> (data) + index;
  64. }
  65. List& add(const T& t) {
  66. if(index >= N) {
  67. return *this;
  68. }
  69. new (end()) T(t);
  70. index++;
  71. return *this;
  72. }
  73. List& add(T&& t) {
  74. if(index >= N) {
  75. return *this;
  76. }
  77. new (end()) T(std::move(t));
  78. index++;
  79. return *this;
  80. }
  81. template<typename... Args>
  82. List& add(Args&&... args) {
  83. if(index >= N) {
  84. return *this;
  85. }
  86. new (end()) T(args...);
  87. index++;
  88. return *this;
  89. }
  90. T& operator[](int index) {
  91. return begin()[index];
  92. }
  93. const T& operator[](int index) const {
  94. return begin()[index];
  95. }
  96. int getLength() const {
  97. return index;
  98. }
  99. template<int L>
  100. void toString(StringBuffer<L>& s) const {
  101. s.append("[");
  102. for(int i = 0; i < index - 1; i++) {
  103. s.append((*this)[i]);
  104. s.append(", ");
  105. }
  106. if(index > 0) {
  107. s.append((*this)[index - 1]);
  108. }
  109. s.append("]");
  110. }
  111. };
  112. #endif