#pragma once #include #include #include #include #include #include #include "utils.h" template class StructSnapshot { public: explicit StructSnapshot(const Structure& source) : source(source), snapshot(source) {} // Compare the live field with the corresponding field in the private snapshot. template bool equals(const Field* field, float tolerance = 0.0001f) const { const auto index = offset(field); if (index >= sizeof(Structure) || sizeof(Field) > sizeof(Structure) - index) { return false; } const auto* previous = reinterpret_cast( reinterpret_cast(&snapshot) + index ); if constexpr (std::is_array_v) { return text(*field) == text(*previous); } else if constexpr (std::is_same_v) { return !isFloatDifferent(*field, *previous, tolerance); } else { return *field == *previous; } } template void set(const Field* field, const Field* value = nullptr) { static_assert(std::is_trivially_copyable_v, "Field must be trivially copyable"); const auto index = offset(field); if (index >= sizeof(Structure) || sizeof(Field) > sizeof(Structure) - index) { return; } std::memcpy(reinterpret_cast(&snapshot) + index, value != nullptr ? value : field, sizeof(Field)); } private: const Structure& source; Structure snapshot; // A fixed-size settings buffer may have no terminator or have unused trailing bytes. template static std::string_view text(const char (&value)[N]) { const std::string_view buffer(value, N); return buffer.substr(0, buffer.find('\0')); } std::size_t offset(const void* field) const { const auto base = reinterpret_cast(&source); const auto address = reinterpret_cast(field); if (field == nullptr || address < base) { return sizeof(Structure); } return address - base; } };