Xteink-X4-crosspoint-reader/lib/Serialization/Serialization.h
Boris Faure 5ae10a7eb6
feat: rework CrossPointSettings
Multiple goals are achieved with this change:
- make descriptions of settings close to their definitions
- settings validation on loading with reset to default in case of bad
  value
- do not boot-loop on bad string values
- (de)serialization is based on a single list of descriptors: single point
  of truth
- possibly to have default values for the String configuration type
- more constexpr to reduce RAM usage
- less hardcoded values
- more maintainable

RAM Usage:
 From
RAM:   [===       ]  32.5% (used 106516 bytes from 327680 bytes)
Flash: [========= ]  94.9% (used 6217240 bytes from 6553600 bytes)
 To
RAM:   [===       ]  32.3% (used 105844 bytes from 327680 bytes)
Flash: [========= ]  94.8% (used 6213378 bytes from 6553600 bytes)

Boot config validation with a test where the status bar config is wrong:
[1256] [SD] SD card detected
[1256] [CPS] Loading settings from file
[1265] [CPS] Invalid value (0x3) for Status Bar, resetting to default
[1265] [CPS] Settings loaded from file
2026-01-28 16:10:45 +01:00

61 lines
1.5 KiB
C++

#pragma once
#include <SdFat.h>
#include <iostream>
namespace serialization {
template <typename T>
static void writePod(std::ostream& os, const T& value) {
os.write(reinterpret_cast<const char*>(&value), sizeof(T));
}
template <typename T>
static void writePod(FsFile& file, const T& value) {
file.write(reinterpret_cast<const uint8_t*>(&value), sizeof(T));
}
template <typename T>
static void readPod(std::istream& is, T& value) {
is.read(reinterpret_cast<char*>(&value), sizeof(T));
}
template <typename T>
static void readPod(FsFile& file, T& value) {
file.read(reinterpret_cast<uint8_t*>(&value), sizeof(T));
}
static void writeString(std::ostream& os, const std::string& s) {
const uint32_t len = s.size();
writePod(os, len);
os.write(s.data(), len);
}
static void writeString(FsFile& file, const std::string& s) {
const uint32_t len = s.size();
writePod(file, len);
file.write(reinterpret_cast<const uint8_t*>(s.data()), len);
}
static void readString(std::istream& is, std::string& s) {
uint32_t len;
readPod(is, len);
s.resize(len);
is.read(&s[0], len);
}
static void readString(FsFile& file, std::string& s) {
uint32_t len;
readPod(file, len);
s.resize(len);
file.read(&s[0], len);
}
static void readString(FsFile& file, char* buffer, size_t maxLen) {
uint32_t len;
readPod(file, len);
const uint32_t bytesToRead = (len < maxLen - 1) ? len : (maxLen - 1);
file.read(reinterpret_cast<uint8_t*>(buffer), bytesToRead);
buffer[bytesToRead] = '\0';
}
} // namespace serialization