1 | // Copyright (C) 2024 The Qt Company Ltd. |
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
3 | |
4 | #ifndef QMAYBE_P_H |
5 | #define QMAYBE_P_H |
6 | |
7 | // |
8 | // W A R N I N G |
9 | // ------------- |
10 | // |
11 | // This file is not part of the Qt API. It exists purely as an |
12 | // implementation detail. This header file may change from version to |
13 | // version without notice, or even be removed. |
14 | // |
15 | // We mean it. |
16 | // |
17 | |
18 | #include <QtCore/private/qglobal_p.h> |
19 | #include <qstring.h> |
20 | #include <optional> |
21 | #include <utility> |
22 | #include <memory> |
23 | |
24 | QT_BEGIN_NAMESPACE |
25 | |
26 | struct QUnexpect |
27 | { |
28 | }; |
29 | |
30 | static constexpr QUnexpect unexpect{}; |
31 | |
32 | template <typename Value, typename Error = QString> |
33 | class QMaybe |
34 | { |
35 | public: |
36 | QMaybe(const Value &v) |
37 | { |
38 | if constexpr (std::is_pointer_v<Value>) { |
39 | if (!v) |
40 | return; // nullptr is treated as nullopt (for raw pointer types only) |
41 | } |
42 | m_value = v; |
43 | } |
44 | |
45 | QMaybe(Value &&v) |
46 | { |
47 | if constexpr (std::is_pointer_v<Value>) { |
48 | if (!v) |
49 | return; // nullptr is treated as nullopt (for raw pointer types only) |
50 | } |
51 | m_value = std::move(v); |
52 | } |
53 | |
54 | QMaybe(const QMaybe &other) = default; |
55 | |
56 | QMaybe &operator=(const QMaybe &other) = default; |
57 | |
58 | QMaybe(const Error &error) : m_error(error) { } |
59 | |
60 | template <class... Args> |
61 | QMaybe(QUnexpect, Args &&...args) : m_error{ std::forward<Args>(args)... } |
62 | { |
63 | static_assert(std::is_constructible_v<Error, Args &&...>, |
64 | "Invalid arguments for creating an error type" ); |
65 | } |
66 | |
67 | constexpr explicit operator bool() const noexcept { return m_value.has_value(); } |
68 | |
69 | constexpr Value &value() |
70 | { |
71 | Q_ASSERT(m_value.has_value()); |
72 | return *m_value; |
73 | } |
74 | |
75 | constexpr const Value &value() const |
76 | { |
77 | Q_ASSERT(m_value.has_value()); |
78 | return *m_value; |
79 | } |
80 | |
81 | constexpr Value *operator->() noexcept { return std::addressof(value()); } |
82 | constexpr const Value *operator->() const noexcept { return std::addressof(value()); } |
83 | |
84 | constexpr Value &operator*() &noexcept { return value(); } |
85 | constexpr const Value &operator*() const &noexcept { return value(); } |
86 | |
87 | constexpr const Error &error() const { return m_error; } |
88 | |
89 | private: |
90 | std::optional<Value> m_value; |
91 | Error m_error; |
92 | }; |
93 | |
94 | QT_END_NAMESPACE |
95 | |
96 | #endif // QMAYBE_P_H |
97 | |