From 4f8828dbee944c956381aec6074b484fa09204a4 Mon Sep 17 00:00:00 2001 From: BlackMark Date: Tue, 7 Apr 2020 05:02:38 +0200 Subject: [PATCH] Implement basic eeprom wrapper for integral and float variables --- eeprom.hpp | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 eeprom.hpp diff --git a/eeprom.hpp b/eeprom.hpp new file mode 100644 index 0000000..dd6e653 --- /dev/null +++ b/eeprom.hpp @@ -0,0 +1,80 @@ +#pragma once + +#include + +#include "../type/type.hpp" + +#define EEVAR(type, name) \ + type EEMEM __##name; \ + constexpr auto name = &__##name + +template +class Eeprom { + public: + operator T() const + { + if constexpr (type::is_integral_v) { + if constexpr (sizeof(T) == 1) { + return eeprom_read_byte(reinterpret_cast(Address)); + } else if constexpr (sizeof(T) == 2) { + return eeprom_read_word(reinterpret_cast(Address)); + } else if constexpr (sizeof(T) == 4) { + return eeprom_read_dword(reinterpret_cast(Address)); + } else if constexpr (sizeof(T) == 8) { + T number; + eeprom_read_block(&number, Address, sizeof(T)); + return number; + } + } else if constexpr (type::is_floating_point_v) { + static_assert(sizeof(T) == 4, "Only floats of size 4 are supported"); + return eeprom_read_float(reinterpret_cast(Address)); + } + } + + Eeprom &operator=(const T &other) + { + if constexpr (type::is_integral_v) { + if constexpr (sizeof(T) == 1) { + if constexpr (Update) { + eeprom_update_byte(reinterpret_cast(Address), other); + } else { + eeprom_write_byte(reinterpret_cast(Address), other); + } + } else if constexpr (sizeof(T) == 2) { + if constexpr (Update) { + eeprom_update_word(reinterpret_cast(Address), other); + } else { + eeprom_write_word(reinterpret_cast(Address), other); + } + } else if constexpr (sizeof(T) == 4) { + if constexpr (Update) { + eeprom_update_dword(reinterpret_cast(Address), other); + } else { + eeprom_write_dword(reinterpret_cast(Address), other); + } + } else if constexpr (sizeof(T) == 8) { + if constexpr (Update) { + eeprom_update_block(&other, Address, sizeof(T)); + } else { + eeprom_write_block(&other, Address, sizeof(T)); + } + } + } else if constexpr (type::is_floating_point_v) { + static_assert(sizeof(T) == 4, "Only floats of size 4 are supported"); + if constexpr (Update) { + eeprom_update_float(reinterpret_cast(Address), other); + } else { + eeprom_write_float(reinterpret_cast(Address), other); + } + } + + return *this; + } + + private: + static_assert(type::is_integral_v || type::is_floating_point_v, + "Only integral and floating point types are supported"); + + static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8, + "Only sizes 1, 2, 4, and 8 are supported"); +};