2014-06-27 22:34:26 +04:00
|
|
|
#ifndef optional_hh_INCLUDED
|
|
|
|
#define optional_hh_INCLUDED
|
|
|
|
|
2015-05-01 20:47:22 +03:00
|
|
|
#include "assert.hh"
|
|
|
|
|
2014-06-27 22:34:26 +04:00
|
|
|
namespace Kakoune
|
|
|
|
{
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
struct Optional
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
constexpr Optional() : m_valid(false) {}
|
|
|
|
Optional(const T& other) : m_valid(true) { new (&m_value) T(other); }
|
|
|
|
Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); }
|
|
|
|
|
|
|
|
Optional(const Optional& other)
|
|
|
|
: m_valid(other.m_valid)
|
|
|
|
{
|
|
|
|
if (m_valid)
|
|
|
|
new (&m_value) T(other.m_value);
|
|
|
|
}
|
|
|
|
|
|
|
|
Optional(Optional&& other)
|
2014-12-25 13:59:06 +03:00
|
|
|
noexcept(noexcept(new (nullptr) T(std::move(other.m_value))))
|
2014-06-27 22:34:26 +04:00
|
|
|
: m_valid(other.m_valid)
|
|
|
|
{
|
|
|
|
if (m_valid)
|
|
|
|
new (&m_value) T(std::move(other.m_value));
|
|
|
|
}
|
|
|
|
|
|
|
|
Optional& operator=(const Optional& other)
|
|
|
|
{
|
2014-12-25 13:59:06 +03:00
|
|
|
destruct_ifn();
|
2014-06-27 22:34:26 +04:00
|
|
|
if ((m_valid = other.m_valid))
|
|
|
|
new (&m_value) T(other.m_value);
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
Optional& operator=(Optional&& other)
|
|
|
|
{
|
2014-12-25 13:59:06 +03:00
|
|
|
destruct_ifn();
|
2014-06-27 22:34:26 +04:00
|
|
|
if ((m_valid = other.m_valid))
|
|
|
|
new (&m_value) T(std::move(other.m_value));
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2014-12-25 13:59:06 +03:00
|
|
|
~Optional() { destruct_ifn(); }
|
2014-06-27 22:34:26 +04:00
|
|
|
|
|
|
|
constexpr explicit operator bool() const noexcept { return m_valid; }
|
|
|
|
|
2014-08-19 21:55:36 +04:00
|
|
|
bool operator==(const Optional& other) const
|
|
|
|
{
|
|
|
|
if (m_valid == other.m_valid)
|
|
|
|
{
|
|
|
|
if (m_valid)
|
|
|
|
return m_value == other.m_value;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2014-06-27 22:34:26 +04:00
|
|
|
T& operator*()
|
|
|
|
{
|
|
|
|
kak_assert(m_valid);
|
|
|
|
return m_value;
|
|
|
|
}
|
|
|
|
const T& operator*() const { return *const_cast<Optional&>(*this); }
|
|
|
|
|
|
|
|
T* operator->()
|
|
|
|
{
|
|
|
|
kak_assert(m_valid);
|
|
|
|
return &m_value;
|
|
|
|
}
|
|
|
|
const T* operator->() const { return const_cast<Optional&>(*this).operator->(); }
|
|
|
|
|
2015-03-14 22:16:46 +03:00
|
|
|
template<typename U>
|
|
|
|
T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; }
|
|
|
|
|
2014-06-27 22:34:26 +04:00
|
|
|
private:
|
2014-12-25 13:59:06 +03:00
|
|
|
void destruct_ifn() { if (m_valid) m_value.~T(); }
|
|
|
|
|
2015-06-25 15:36:45 +03:00
|
|
|
union
|
|
|
|
{
|
|
|
|
struct {} m_empty; // disable default construction of value
|
|
|
|
T m_value;
|
|
|
|
};
|
2015-04-15 13:43:39 +03:00
|
|
|
bool m_valid;
|
2014-06-27 22:34:26 +04:00
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif // optional_hh_INCLUDED
|