List.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. void clear() {
  22. for(int i = 0; i < index; i++) {
  23. (*this)[i].~T();
  24. }
  25. index = 0;
  26. }
  27. ~List() {
  28. clear();
  29. }
  30. List(const List& other) : index(0) {
  31. copy(other);
  32. }
  33. List& operator=(const List& other) {
  34. if(&other != this) {
  35. clear();
  36. copy(other);
  37. }
  38. return *this;
  39. }
  40. List(List&& other) : index(0) {
  41. move(std::move(other));
  42. other.clear();
  43. }
  44. List& operator=(List&& other) {
  45. if(&other != this) {
  46. clear();
  47. move(std::move(other));
  48. other.clear();
  49. }
  50. return *this;
  51. }
  52. T* begin() {
  53. return reinterpret_cast<T*> (data);
  54. }
  55. T* end() {
  56. return reinterpret_cast<T*> (data) + index;
  57. }
  58. const T* begin() const {
  59. return reinterpret_cast<const T*> (data);
  60. }
  61. const T* end() const {
  62. return reinterpret_cast<const T*> (data) + index;
  63. }
  64. void add(const T& t) {
  65. if(index >= N) {
  66. return;
  67. }
  68. new (end()) T(t);
  69. index++;
  70. }
  71. void add(T&& t) {
  72. if(index >= N) {
  73. return;
  74. }
  75. new (end()) T(std::move(t));
  76. index++;
  77. }
  78. template<typename... Args>
  79. void add(Args&&... args) {
  80. if(index >= N) {
  81. return;
  82. }
  83. new (end()) T(args...);
  84. index++;
  85. }
  86. T& operator[](int index) {
  87. return begin()[index];
  88. }
  89. const T& operator[](int index) const {
  90. return begin()[index];
  91. }
  92. int getLength() const {
  93. return index;
  94. }
  95. template<int L>
  96. void toString(StringBuffer<L>& s) const {
  97. s.append("[");
  98. for(int i = 0; i < index - 1; i++) {
  99. s.append((*this)[i]);
  100. s.append(", ");
  101. }
  102. if(index > 0) {
  103. s.append((*this)[index - 1]);
  104. }
  105. s.append("]");
  106. }
  107. };
  108. #endif