| 1 |
/// @file |
| 2 |
/// @brief C analog of C++’s `std::optional` |
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#include <assert.h> |
| 7 |
#include <stdbool.h> |
| 8 |
#include <stddef.h> |
| 9 |
|
| 10 |
/// a container that may or may not contain a `double` value |
| 11 |
typedef struct { |
| 12 |
bool has_value; ///< does this have a value? |
| 13 |
double value; ///< the value if `has_value` is true |
| 14 |
} optional_double_t; |
| 15 |
|
| 16 |
/// set the value of an optional |
| 17 |
/// |
| 18 |
/// This utility function is intended to avoid the easy typo of setting the |
| 19 |
/// value while forgetting to set the `has_value` member. |
| 20 |
/// |
| 21 |
/// @param me The optional whose value to set |
| 22 |
/// @param value The value to assign |
| 23 |
static inline void optional_double_set(optional_double_t *me, double value) { |
| 24 |
assert(me != NULL); |
| 25 |
me->has_value = true; |
| 26 |
me->value = value; |
| 27 |
} |
| 28 |
|
| 29 |
/// get the value of an optional or a given value if the optional is empty |
| 30 |
/// |
| 31 |
/// @param me The optional whose value to retrieve |
| 32 |
/// @param fallback The value to return if the optional is empty |
| 33 |
/// @return Value of the optional or `fallback` if it was empty |
| 34 |
static inline double optional_double_value_or(optional_double_t me, |
| 35 |
double fallback) { |
| 36 |
if (me.has_value) { |
| 37 |
return me.value; |
| 38 |
} |
| 39 |
return fallback; |
| 40 |
} |