Skip to content

Commit

Permalink
feat(reflection): add resize & clear to array
Browse files Browse the repository at this point in the history
  • Loading branch information
RiscadoA committed Nov 12, 2023
1 parent 6ac6f55 commit 24cfdaa
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/include/cubos/core/reflection/traits/array.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ namespace cubos::core::reflection
/// @return Whether the operation is supported.
bool hasErase() const;

/// @brief Checks if resize is supported.
/// @return Whether the operation is supported.
bool hasResize() const;

/// @brief Returns the element type of the array.
/// @return Element type.
const Type& elementType() const;
Expand Down Expand Up @@ -159,6 +163,16 @@ namespace cubos::core::reflection
/// @param index Element index.
void erase(std::size_t index) const;

/// @brief Clears the array.
/// @note Aborts if @ref ArrayTrait::hasErase() returns false.
void clear() const;

/// @brief Resizes the array. If this increases the size of the array, @ref insertDefault
/// is used to insert the remaining elements.
/// @note Aborts if @ref ArrayTrait::hasResize() returns false.
/// @param size Array size.
void resize(std::size_t size) const;

/// @brief Gets an iterator to the first element.
/// @return Iterator.
Iterator begin() const;
Expand Down
34 changes: 34 additions & 0 deletions core/src/cubos/core/reflection/traits/array.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ bool ArrayTrait::hasErase() const
return mErase != nullptr;
}

bool ArrayTrait::hasResize() const
{
return this->hasErase() && this->hasInsertDefault();
}

const Type& ArrayTrait::elementType() const
{
return mElementType;
Expand Down Expand Up @@ -111,6 +116,35 @@ void ArrayTrait::View::erase(std::size_t index) const
mTrait.mErase(mInstance, index);
}

void ArrayTrait::View::clear() const
{
CUBOS_ASSERT(mTrait.hasErase(), "Clear not supported");

// This really inefficient, but if it ever becomes a problem its easy to improve, we could just
// add yet another function pointer to the trait, which each array type sets.
while (this->length() > 0)
{
this->erase(this->length() - 1);
}
}

void ArrayTrait::View::resize(std::size_t size) const
{
CUBOS_ASSERT(mTrait.hasResize(), "Resize not supported");

// This really inefficient, but if it ever becomes a problem its easy to improve, we could just
// add yet another function pointer to the trait, which each array type sets.
while (this->length() > size)
{
this->erase(this->length() - 1);
}

while (this->length() < size)
{
this->insertDefault(this->length());
}
}

ArrayTrait::View::Iterator ArrayTrait::View::begin() const
{
return Iterator{*this, 0};
Expand Down

0 comments on commit 24cfdaa

Please sign in to comment.