File indexing completed on 2024-04-06 12:01:18
0001 #ifndef CommonTools_Utils_DynArray_H
0002 #define CommonTools_Utils_DynArray_H
0003
0004 template <typename T>
0005 class DynArray {
0006 public:
0007 T* a = nullptr;
0008 unsigned int s = 0;
0009
0010 public:
0011 using size_type = unsigned int;
0012 using value_type = T;
0013 using reference = T&;
0014 using const_reference = T const&;
0015
0016 DynArray() {}
0017
0018 explicit DynArray(unsigned char* storage) : a((T*)(storage)), s(0) {}
0019
0020 DynArray(unsigned char* storage, unsigned int isize) : a((T*)(storage)), s(isize) {
0021 for (auto i = 0U; i < s; ++i)
0022 new ((begin() + i)) T();
0023 }
0024 DynArray(unsigned char* storage, unsigned int isize, T const& it) : a((T*)(storage)), s(isize) {
0025 for (auto i = 0U; i < s; ++i)
0026 new ((begin() + i)) T(it);
0027 }
0028
0029 DynArray(DynArray const&) = delete;
0030 DynArray& operator=(DynArray const&) = delete;
0031
0032 DynArray(DynArray&& other) {
0033 a = other.a;
0034 s = other.s;
0035 other.s = 0;
0036 other.a = nullptr;
0037 }
0038 DynArray& operator=(DynArray&& other) {
0039 a = other.a;
0040 s = other.s;
0041 other.s = 0;
0042 other.a = nullptr;
0043 return *this;
0044 }
0045
0046 ~DynArray() {
0047 for (auto i = 0U; i < s; ++i)
0048 a[i].~T();
0049 }
0050
0051 T& operator[](unsigned int i) { return a[i]; }
0052 T* begin() { return a; }
0053 T* end() { return a + s; }
0054 T& front() { return a[0]; }
0055 T& back() { return a[s - 1]; }
0056
0057 T const& operator[](unsigned int i) const { return a[i]; }
0058 T const* begin() const { return a; }
0059 T const* end() const { return a + s; }
0060 unsigned int size() const { return s; }
0061 bool empty() const { return 0 == s; }
0062
0063 T const* data() const { return a; }
0064 T const& front() const { return a[0]; }
0065 T const& back() const { return a[s - 1]; }
0066
0067 void pop_back() {
0068 back().~T();
0069 --s;
0070 }
0071 void push_back(T const& t) {
0072 new ((begin() + s)) T(t);
0073 ++s;
0074 }
0075 void push_back(T&& t) {
0076 new ((begin() + s)) T(t);
0077 ++s;
0078 }
0079 };
0080
0081 namespace dynarray {
0082 template <typename T>
0083 inline T num(T s) {
0084 return s > 0 ? s : T(1);
0085 }
0086 }
0087
0088 #define unInitDynArray(T, n, x) \
0089 alignas(alignof(T)) unsigned char x##_storage[sizeof(T) * dynarray::num(n)]; \
0090 DynArray<T> x(x##_storage)
0091 #define declareDynArray(T, n, x) \
0092 alignas(alignof(T)) unsigned char x##_storage[sizeof(T) * dynarray::num(n)]; \
0093 DynArray<T> x(x##_storage, n)
0094 #define initDynArray(T, n, x, i) \
0095 alignas(alignof(T)) unsigned char x##_storage[sizeof(T) * dynarray::num(n)]; \
0096 DynArray<T> x(x##_storage, n, i)
0097
0098 #endif