[ox/std] Add AnyPtr

This commit is contained in:
Gary Talent 2024-03-23 16:52:43 -05:00
parent 27f1df8f33
commit 3fa247e3d4
4 changed files with 75 additions and 1 deletions

73
deps/ox/src/ox/std/anyptr.hpp vendored Normal file
View File

@ -0,0 +1,73 @@
#pragma once
#include "array.hpp"
#include "span.hpp"
namespace ox {
class AnyPtr {
private:
struct WrapBase {
virtual ~WrapBase() = default;
virtual WrapBase *copyTo(ox::Span<char> s) noexcept = 0;
virtual operator bool() const noexcept = 0;
};
template<typename T>
struct Wrap: public WrapBase {
T *data{};
constexpr Wrap(T *pData) noexcept: data(pData) {
}
inline WrapBase *copyTo(ox::Span<char> s) noexcept override {
return new(s.data()) Wrap{data};
}
constexpr operator bool() const noexcept override {
return data != nullptr;
}
};
WrapBase *m_wrapPtr{};
ox::Array<char, sizeof(Wrap<void*>)> m_wrapData;
public:
constexpr AnyPtr() noexcept = default;
template<typename T>
inline AnyPtr(T *ptr) noexcept {
m_wrapPtr = new(m_wrapData.data()) Wrap(ptr);
}
inline AnyPtr(AnyPtr const&other) noexcept {
if (other) {
m_wrapPtr = other.m_wrapPtr->copyTo(m_wrapData);
}
}
template<typename T>
inline AnyPtr &operator=(T *ptr) noexcept {
m_wrapPtr = new(m_wrapData.data()) Wrap(ptr);
return *this;
}
inline AnyPtr &operator=(AnyPtr const&ptr) noexcept {
if (this != &ptr) {
if (ptr) {
m_wrapPtr = ptr.m_wrapPtr->copyTo(m_wrapData);
} else {
m_wrapPtr = nullptr;
}
}
return *this;
}
constexpr operator bool() const noexcept {
return m_wrapPtr && *m_wrapPtr;
}
template<typename T>
[[nodiscard]]
constexpr T *get() const noexcept {
#ifdef OX_BARE_METAL
auto const out = static_cast<Wrap<T>*>(m_wrapPtr);
#else
auto const out = dynamic_cast<Wrap<T>*>(m_wrapPtr);
#endif
return out->data;
}
};
}

View File

@ -13,7 +13,6 @@
#include "initializerlist.hpp" #include "initializerlist.hpp"
#include "iterator.hpp" #include "iterator.hpp"
#include "math.hpp" #include "math.hpp"
#include "memory.hpp"
#include "new.hpp" #include "new.hpp"
#include "types.hpp" #include "types.hpp"
#include "utility.hpp" #include "utility.hpp"

View File

@ -8,6 +8,7 @@
#pragma once #pragma once
#include "array.hpp"
#include "bit.hpp" #include "bit.hpp"
#include "iterator.hpp" #include "iterator.hpp"
#include "vector.hpp" #include "vector.hpp"

View File

@ -8,6 +8,7 @@
#pragma once #pragma once
#include "anyptr.hpp"
#include "array.hpp" #include "array.hpp"
#include "assert.hpp" #include "assert.hpp"
#include "bit.hpp" #include "bit.hpp"