ArrayList.hpp 2.9 KB

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