summaryrefslogtreecommitdiff
path: root/src/optional.hh
blob: 3f919043704bde12c66e039528b745879813b424 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#ifndef optional_hh_INCLUDED
#define optional_hh_INCLUDED

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)
        noexcept(noexcept(new ((void*)0) T(std::move(other.m_value))))
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(std::move(other.m_value));
    }

    Optional& operator=(const Optional& other)
    {
        if (m_valid)
            m_value.~T();
        if ((m_valid = other.m_valid))
            new (&m_value) T(other.m_value);
        return *this;
    }

    Optional& operator=(Optional&& other)
    {
        if (m_valid)
            m_value.~T();
        if ((m_valid = other.m_valid))
            new (&m_value) T(std::move(other.m_value));
        return *this;
    }

    ~Optional()
    {
        if (m_valid)
            m_value.~T();
    }

    constexpr explicit operator bool() const noexcept { return m_valid; }

    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;
    }

    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->(); }

private:
    bool m_valid;
    union { T m_value; };
};

}

#endif // optional_hh_INCLUDED