File: optional.h

package info (click to toggle)
graphviz 14.0.5-2
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 139,388 kB
  • sloc: ansic: 141,938; cpp: 11,957; python: 7,766; makefile: 4,043; yacc: 3,030; xml: 2,972; tcl: 2,495; sh: 1,388; objc: 1,159; java: 560; lex: 423; perl: 243; awk: 156; pascal: 139; php: 58; ruby: 49; cs: 31; sed: 1
file content (40 lines) | stat: -rw-r--r-- 1,203 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// @file
/// @brief C analog of C++’s `std::optional`

#pragma once

#include <assert.h>
#include <stdbool.h>
#include <stddef.h>

/// a container that may or may not contain a `double` value
typedef struct {
  bool has_value; ///< does this have a value?
  double value;   ///< the value if `has_value` is true
} optional_double_t;

/// set the value of an optional
///
/// This utility function is intended to avoid the easy typo of setting the
/// value while forgetting to set the `has_value` member.
///
/// @param me The optional whose value to set
/// @param value The value to assign
static inline void optional_double_set(optional_double_t *me, double value) {
  assert(me != NULL);
  me->has_value = true;
  me->value = value;
}

/// get the value of an optional or a given value if the optional is empty
///
/// @param me The optional whose value to retrieve
/// @param fallback The value to return if the optional is empty
/// @return Value of the optional or `fallback` if it was empty
static inline double optional_double_value_or(optional_double_t me,
                                              double fallback) {
  if (me.has_value) {
    return me.value;
  }
  return fallback;
}