summaryrefslogtreecommitdiff
path: root/utilities.hpp
blob: 819c170638c981688611492fcf58ecca65ccc253 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#ifndef THROTTLE_QUADRANT_UTILITIES_HPP
#define THROTTLE_QUADRANT_UTILITIES_HPP

#include <Arduino.h>

void* operator new(size_t size, void* ptr);

namespace tq {

template<typename ValueType>
struct optional {

  optional()
    : m_engaged{ false } {
  }

  optional(optional const& other)
    : m_engaged{ other.has_value() } {
    if (m_engaged) {
      construct_from(other.value());
    }
  }

  explicit optional(ValueType const& value)
    : m_engaged{ true } {
    construct_from(value);
  }

  ~optional() {
    destroy();
  }

  auto operator=(optional const& other) -> optional& {
    destroy();
    m_engaged = other.m_engaged;
    if (m_engaged) {
      construct_from(other.value());
    }
  }

  auto has_value() const -> bool {
    return m_engaged;
  }

  auto value() const -> ValueType const& {
    return *(reinterpret_cast<ValueType const*>(m_storage));
  }

private:
  auto construct_from(ValueType const& value) -> void {
    new (static_cast<byte*>(m_storage)) ValueType{ value };
  }

  auto destroy() -> void {
    if (has_value()) {
      (reinterpret_cast<ValueType const*>(m_storage))->~ValueType();
    }
  }

  alignas(ValueType) byte m_storage[sizeof(ValueType)];
  bool m_engaged;
};


}

#endif