1 | //===-- Holds an expected or unexpected value -------------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #ifndef LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H |
10 | #define LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H |
11 | |
12 | namespace LIBC_NAMESPACE::cpp { |
13 | |
14 | // This is used to hold an unexpected value so that a different constructor is |
15 | // selected. |
16 | template <class T> class unexpected { |
17 | T value; |
18 | |
19 | public: |
20 | constexpr explicit unexpected(T value) : value(value) {} |
21 | constexpr T error() { return value; } |
22 | }; |
23 | |
24 | template <class T, class E> class expected { |
25 | union { |
26 | T exp; |
27 | E unexp; |
28 | }; |
29 | bool is_expected; |
30 | |
31 | public: |
32 | constexpr expected(T exp) : exp(exp), is_expected(true) {} |
33 | constexpr expected(unexpected<E> unexp) |
34 | : unexp(unexp.error()), is_expected(false) {} |
35 | |
36 | constexpr bool has_value() const { return is_expected; } |
37 | |
38 | constexpr T &value() { return exp; } |
39 | constexpr E &error() { return unexp; } |
40 | constexpr const T &value() const { return exp; } |
41 | constexpr const E &error() const { return unexp; } |
42 | |
43 | constexpr operator bool() const { return is_expected; } |
44 | |
45 | constexpr T &operator*() { return exp; } |
46 | constexpr const T &operator*() const { return exp; } |
47 | constexpr T *operator->() { return &exp; } |
48 | constexpr const T *operator->() const { return &exp; } |
49 | }; |
50 | |
51 | } // namespace LIBC_NAMESPACE::cpp |
52 | |
53 | #endif // LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H |
54 | |