aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/misc/optional.h
blob: d5e3c07fbe05773d1b41b865aec787c69507613a (plain) (blame)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#pragma once

#include <util/string/cast.h>

#include <optional>

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

template <class T>
struct TOptionalTraits
{
    using TOptional = std::optional<T>;
    using TValue = T;

    static constexpr bool HasValue(const TOptional& opt)
    {
        return opt.has_value();
    }

    static constexpr TOptional Empty()
    {
        return std::nullopt;
    }
};

template <class T>
struct TOptionalTraits<std::optional<T>>
{
    using TOptional = std::optional<T>;
    using TValue = T;

    static constexpr bool HasValue(const TOptional& opt)
    {
        return opt.has_value();
    }

    static constexpr TOptional Empty()
    {
        return std::nullopt;
    }
};

template <class T>
struct TOptionalTraits<T*>
{
    using TOptional = T*;
    using TValue = T*;

    static constexpr bool HasValue(const TOptional& opt)
    {
        return opt != nullptr;
    }

    static constexpr TOptional Empty()
    {
        return nullptr;
    }
};

template <class T>
struct TOptionalTraits<TIntrusivePtr<T>>
{
    using TOptional = TIntrusivePtr<T>;
    using TValue = TIntrusivePtr<T>;

    static bool HasValue(const TOptional& opt)
    {
        return opt.Get() != nullptr;
    }

    static constexpr TOptional Empty()
    {
        return TIntrusivePtr<T>{};
    }
};

////////////////////////////////////////////////////////////////////////////////

template <class T>
struct TStdOptionalTraits
{
    static constexpr bool IsStdOptional = false;
    using TValueType = T;
};

template <class T>
struct TStdOptionalTraits<std::optional<T>>
{
    static constexpr bool IsStdOptional = true;
    using TValueType = T;
};

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT

template <class T>
TString ToString(const std::optional<T>& nullable)
{
    return nullable ? ToString(*nullable) : "<Null>";
}

template <class T>
struct THash<std::optional<T>>
{
    size_t operator()(const std::optional<T>& nullable) const
    {
        return nullable ? THash<T>()(*nullable) : 0;
    }
};