xref: /aosp_15_r20/external/llvm-libc/src/__support/CPP/expected.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
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 #include "src/__support/macros/attributes.h"
13 #include "src/__support/macros/config.h"
14 
15 namespace LIBC_NAMESPACE_DECL {
16 namespace cpp {
17 
18 // This is used to hold an unexpected value so that a different constructor is
19 // selected.
20 template <class T> class unexpected {
21   T value;
22 
23 public:
unexpected(T value)24   LIBC_INLINE constexpr explicit unexpected(T value) : value(value) {}
error()25   LIBC_INLINE constexpr T error() { return value; }
26 };
27 
28 template <class T> explicit unexpected(T) -> unexpected<T>;
29 
30 template <class T, class E> class expected {
31   union {
32     T exp;
33     E unexp;
34   };
35   bool is_expected;
36 
37 public:
expected(T exp)38   LIBC_INLINE constexpr expected(T exp) : exp(exp), is_expected(true) {}
expected(unexpected<E> unexp)39   LIBC_INLINE constexpr expected(unexpected<E> unexp)
40       : unexp(unexp.error()), is_expected(false) {}
41 
has_value()42   LIBC_INLINE constexpr bool has_value() const { return is_expected; }
43 
value()44   LIBC_INLINE constexpr T &value() { return exp; }
error()45   LIBC_INLINE constexpr E &error() { return unexp; }
value()46   LIBC_INLINE constexpr const T &value() const { return exp; }
error()47   LIBC_INLINE constexpr const E &error() const { return unexp; }
48 
49   LIBC_INLINE constexpr operator bool() const { return is_expected; }
50 
51   LIBC_INLINE constexpr T &operator*() { return exp; }
52   LIBC_INLINE constexpr const T &operator*() const { return exp; }
53   LIBC_INLINE constexpr T *operator->() { return &exp; }
54   LIBC_INLINE constexpr const T *operator->() const { return &exp; }
55 };
56 
57 } // namespace cpp
58 } // namespace LIBC_NAMESPACE_DECL
59 
60 #endif // LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H
61