ArrayList.h 2.5 KB

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