rusEFI
An attempt to build an Engine Control Unit
expected.h
Go to the documentation of this file.
1 /**
2  * @file expected.h
3  * @brief This utility class provides a way for a function to accept or return a value that may be invalid.
4  *
5  * For example, suppose there needs to be a solution for prevention of divide by zero. One could write this function:
6  *
7  * expected<int> my_divide(int num, int denom) {
8  * if (denom == 0) return unexpected;
9  * return num / denom;
10  * }
11  *
12  * @date April 18, 2020
13  * @author Matthew Kennedy, (c) 2020
14  */
15 
16 #pragma once
17 
18 struct unexpected_t {};
19 
20 enum class UnexpectedCode : char {
21  Unknown = 0,
22 
23  // Too much time has passed
24  Timeout,
25 
26  // The decoded value was impossibly high/low
27  High,
28  Low,
29 
30  // An inconsistency was detected using multiple sources of information
32 
33  // A value is unavailable due to configuration
35 };
36 template <class TValue>
37 struct expected {
38  bool Valid;
39 
40  union {
41  TValue Value;
43  };
44 
45  // Implicit constructor to construct in the invalid state
46  constexpr expected(const unexpected_t&) : Valid(false), Code{UnexpectedCode::Unknown} {}
47 
48  constexpr expected(UnexpectedCode code) : Valid(false), Code{code} {}
49 
50  // Implicit constructor to convert from TValue (for valid values, so an expected<T> behaves like a T)
51  constexpr expected(TValue validValue)
52  : Valid(true)
53  , Value(validValue)
54  {
55  }
56 
57  // Implicit conversion operator to bool, so you can do things like if (myResult) { ... }
58  constexpr explicit operator bool() const {
59  return Valid;
60  }
61 
62  // Easy default value handling
63  constexpr TValue value_or(TValue valueIfInvalid) const {
64  return Valid ? Value : valueIfInvalid;
65  }
66 
67  bool operator ==(const expected<TValue>& other) const {
68  // If validity mismatch, not equal
69  if (Valid != other.Valid) {
70  return false;
71  }
72 
73  // If both are invalid, they are equal
74  if (!Valid && !other.Valid) {
75  return true;
76  }
77 
78  // Both are guaranteed valid - simply compare values
79  return Value == other.Value;
80  }
81 };
82 
uint8_t code
Definition: bluetooth.cpp:39
constexpr unexpected_t unexpected
Definition: expected.h:83
UnexpectedCode
Definition: expected.h:20
constexpr expected(UnexpectedCode code)
Definition: expected.h:48
constexpr TValue value_or(TValue valueIfInvalid) const
Definition: expected.h:63
constexpr expected(TValue validValue)
Definition: expected.h:51
bool Valid
Definition: expected.h:38
TValue Value
Definition: expected.h:41
constexpr expected(const unexpected_t &)
Definition: expected.h:46
bool operator==(const expected< TValue > &other) const
Definition: expected.h:67
UnexpectedCode Code
Definition: expected.h:42