SensESP 3.0.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
nullable.h
Go to the documentation of this file.
1#ifndef SENSESP_SRC_SENSESP_TYPES_NULLABLE_H_
2#define SENSESP_SRC_SENSESP_TYPES_NULLABLE_H_
3
4#include "ArduinoJson.h"
5
6namespace sensesp {
7
14template <typename T>
15class Nullable {
16 public:
17 Nullable() : value_{} {}
18 Nullable(T value) : value_{value} {}
20 value_ = value;
21 return *this;
22 }
24 value_ = other.value_;
25 return *this;
26 }
27 operator T() const {
28 return value_;
29 }
30
31 bool is_valid() const {
32 return value_ != invalid_value_;
33 }
34
35 T* ptr() {
36 return &value_;
37 }
38
39 static T invalid() {
40 return invalid_value_;
41 }
42
43 T value() const {
44 return value_;
45 }
46
47 private:
48 T value_;
49 static T invalid_value_;
50};
51
56
57template <typename T>
58void convertFromJson(JsonVariantConst src, Nullable<T> &dst) {
59 if (src.isNull()) {
61 } else {
62 dst = src.as<T>();
63 }
64}
65
66template <typename T>
67void convertToJson(const Nullable<T> &src, JsonVariant dst) {
68 if (src.is_valid()) {
69 dst.set(src.value());
70 } else {
71 dst.clear();
72 }
73}
74
75} // namespace sensesp
76
77#endif // SENSESP_SRC_SENSESP_TYPES_NULLABLE_H_
Template class that supports a special invalid magic value for a type.
Definition nullable.h:15
Nullable< T > & operator=(T &value)
Definition nullable.h:19
Nullable< T > & operator=(const Nullable< T > &other)
Definition nullable.h:23
T value() const
Definition nullable.h:43
static T invalid()
Definition nullable.h:39
Nullable(T value)
Definition nullable.h:18
bool is_valid() const
Definition nullable.h:31
Nullable< bool > NullableBool
Definition nullable.h:55
Nullable< int > NullableInt
Definition nullable.h:52
void convertToJson(const Nullable< T > &src, JsonVariant dst)
Definition nullable.h:67
Nullable< double > NullableDouble
Definition nullable.h:54
void convertFromJson(JsonVariantConst src, Nullable< T > &dst)
Definition nullable.h:58
Nullable< float > NullableFloat
Definition nullable.h:53