Skip to content

Commit

Permalink
SDK: Add TArray move constructor/common operations
Browse files Browse the repository at this point in the history
  • Loading branch information
praydog committed Oct 28, 2023
1 parent 531e433 commit 7ea4617
Showing 1 changed file with 88 additions and 4 deletions.
92 changes: 88 additions & 4 deletions shared/sdk/TArray.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <type_traits>
#include <sdk/FMalloc.hpp>

namespace sdk {
Expand All @@ -12,20 +13,103 @@ struct TArrayLite {

template<typename T>
struct TArray {
T* data{nullptr};
int32_t count{0};
int32_t capacity{0};

// Move constructor
TArray(TArray&& other) noexcept
: data(other.data),
count(other.count),
capacity(other.capacity)
{
other.data = nullptr;
other.count = 0;
other.capacity = 0;
}

// Move assignment operator
TArray& operator=(TArray&& other) noexcept {
if (&other != this) {
if (data != nullptr) {
this->~TArray(); // call destructor to free the current data
}

data = other.data;
count = other.count;
capacity = other.capacity;

other.data = nullptr;
other.count = 0;
other.capacity = 0;
}

return *this;
}

TArray() = default;

// Delete copy constructor and copy assignment operator
TArray(const TArray&) = delete;
TArray& operator=(const TArray&) = delete;

~TArray() {
if (data == nullptr) {
return;
}

// TODO: call destructors?
if constexpr (!std::is_trivially_destructible_v<T>) {
for (auto i = 0; i < count; ++i) {
data[i].~T();
}
}

if (auto m = FMalloc::get(); m != nullptr) {
m->free(data);
}

data = nullptr;
}

T* data{nullptr};
int32_t count{0};
int32_t capacity{0};
// begin/end
T* begin() {
return data;
}

T* end() {
return data + count;
}

// operator[]
T& operator[](int32_t index) {
return data[index];
}

const T& operator[](int32_t index) const {
return data[index];
}

// size
int32_t size() const {
return count;
}

// empty
bool empty() const {
return count == 0;
}

void clear(bool shrink = true) {
// trigger destructors
if constexpr (!std::is_trivially_destructible_v<T>) {
for (auto i = 0; i < count; ++i) {
data[i].~T();
}
}

count = 0;
}

// todo: push_back and stuff...
};
}

0 comments on commit 7ea4617

Please sign in to comment.