2022-04-10 00:17:06 +00:00
|
|
|
#ifndef _RSTL_OPTIONAL_OBJECT_HPP
|
|
|
|
#define _RSTL_OPTIONAL_OBJECT_HPP
|
|
|
|
|
|
|
|
#include "types.h"
|
|
|
|
|
2022-08-09 23:03:51 +00:00
|
|
|
#include "rstl/construct.hpp"
|
2022-04-10 00:17:06 +00:00
|
|
|
|
|
|
|
namespace rstl {
|
2022-09-18 06:16:53 +00:00
|
|
|
struct optional_object_null {};
|
|
|
|
|
2022-04-10 00:17:06 +00:00
|
|
|
template < typename T >
|
|
|
|
class optional_object {
|
|
|
|
public:
|
2022-09-18 05:55:13 +00:00
|
|
|
optional_object() : m_valid(false) {}
|
2022-09-18 06:16:53 +00:00
|
|
|
optional_object(optional_object_null) : m_valid(false) {}
|
2022-09-18 05:55:13 +00:00
|
|
|
optional_object(const T& item) : m_valid(true) { rstl::construct< T >(m_data, item); }
|
|
|
|
optional_object(const optional_object& other) : m_valid(other.m_valid) {
|
|
|
|
if (other.m_valid) {
|
|
|
|
rstl::construct< T >(m_data, other.data());
|
|
|
|
}
|
|
|
|
}
|
2022-04-10 00:17:06 +00:00
|
|
|
~optional_object() { clear(); }
|
|
|
|
|
2022-09-13 04:26:54 +00:00
|
|
|
optional_object& operator=(const T& item) {
|
|
|
|
assign(item);
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2022-09-18 05:55:13 +00:00
|
|
|
T& data() { return *get_ptr(); }
|
|
|
|
const T& data() const { return *get_ptr(); }
|
|
|
|
T* get_ptr() { return reinterpret_cast< T* >(m_data); }
|
|
|
|
const T* get_ptr() const { return reinterpret_cast< const T* >(m_data); }
|
|
|
|
bool valid() const { return m_valid; }
|
|
|
|
operator bool() const { return m_valid; } // replace with valid()?
|
2022-04-10 00:17:06 +00:00
|
|
|
void clear() {
|
2022-09-18 05:55:13 +00:00
|
|
|
if (m_valid) {
|
|
|
|
rstl::destroy(get_ptr());
|
|
|
|
}
|
|
|
|
m_valid = false;
|
2022-04-10 00:17:06 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 04:26:54 +00:00
|
|
|
T& operator*() { return data(); }
|
2022-09-18 05:55:13 +00:00
|
|
|
T* operator->() { return data(); }
|
2022-09-13 04:26:54 +00:00
|
|
|
|
2022-04-10 00:17:06 +00:00
|
|
|
private:
|
2022-09-18 05:55:13 +00:00
|
|
|
u8 m_data[sizeof(T)];
|
|
|
|
bool m_valid;
|
2022-09-13 04:26:54 +00:00
|
|
|
|
|
|
|
void assign(const T& item) {
|
2022-09-18 05:55:13 +00:00
|
|
|
if (!m_valid) {
|
2022-09-13 04:26:54 +00:00
|
|
|
rstl::construct(get_ptr(), item);
|
2022-09-18 05:55:13 +00:00
|
|
|
m_valid = true;
|
2022-09-13 04:26:54 +00:00
|
|
|
} else {
|
|
|
|
data() = item;
|
|
|
|
}
|
|
|
|
}
|
2022-04-10 00:17:06 +00:00
|
|
|
};
|
|
|
|
} // namespace rstl
|
|
|
|
|
|
|
|
#endif
|