ArrayList.h 2.4 KB

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