• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
14 namespace LIBC_NAMESPACE::cpp {
15 
16 // This is used to hold an unexpected value so that a different constructor is
17 // selected.
18 template <class T> class unexpected {
19   T value;
20 
21 public:
unexpected(T value)22   LIBC_INLINE constexpr explicit unexpected(T value) : value(value) {}
error()23   LIBC_INLINE constexpr T error() { return value; }
24 };
25 
26 template <class T> explicit unexpected(T) -> unexpected<T>;
27 
28 template <class T, class E> class expected {
29   union {
30     T exp;
31     E unexp;
32   };
33   bool is_expected;
34 
35 public:
expected(T exp)36   LIBC_INLINE constexpr expected(T exp) : exp(exp), is_expected(true) {}
expected(unexpected<E> unexp)37   LIBC_INLINE constexpr expected(unexpected<E> unexp)
38       : unexp(unexp.error()), is_expected(false) {}
39 
has_value()40   LIBC_INLINE constexpr bool has_value() const { return is_expected; }
41 
value()42   LIBC_INLINE constexpr T &value() { return exp; }
error()43   LIBC_INLINE constexpr E &error() { return unexp; }
value()44   LIBC_INLINE constexpr const T &value() const { return exp; }
error()45   LIBC_INLINE constexpr const E &error() const { return unexp; }
46 
47   LIBC_INLINE constexpr operator bool() const { return is_expected; }
48 
49   LIBC_INLINE constexpr T &operator*() { return exp; }
50   LIBC_INLINE constexpr const T &operator*() const { return exp; }
51   LIBC_INLINE constexpr T *operator->() { return &exp; }
52   LIBC_INLINE constexpr const T *operator->() const { return &exp; }
53 };
54 
55 } // namespace LIBC_NAMESPACE::cpp
56 
57 #endif // LLVM_LIBC_SRC___SUPPORT_CPP_EXPECTED_H
58