From 657978b416909f48dac5b5109a5b2f8f2913b127 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 17 Jan 2026 11:38:29 -1000 Subject: [PATCH] [core] Add fnv1_hash_extend() string overloads, use in atm90e32 --- esphome/components/atm90e32/atm90e32.cpp | 9 ++++++--- esphome/core/helpers.h | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/esphome/components/atm90e32/atm90e32.cpp b/esphome/components/atm90e32/atm90e32.cpp index 634260b5e9..f4c199cb98 100644 --- a/esphome/components/atm90e32/atm90e32.cpp +++ b/esphome/components/atm90e32/atm90e32.cpp @@ -158,12 +158,14 @@ void ATM90E32Component::setup() { if (this->enable_offset_calibration_) { // Initialize flash storage for offset calibrations - uint32_t o_hash = fnv1_hash(std::string("_offset_calibration_") + this->cs_summary_); + uint32_t o_hash = fnv1_hash("_offset_calibration_"); + o_hash = fnv1_hash_extend(o_hash, this->cs_summary_); this->offset_pref_ = global_preferences->make_preference(o_hash, true); this->restore_offset_calibrations_(); // Initialize flash storage for power offset calibrations - uint32_t po_hash = fnv1_hash(std::string("_power_offset_calibration_") + this->cs_summary_); + uint32_t po_hash = fnv1_hash("_power_offset_calibration_"); + po_hash = fnv1_hash_extend(po_hash, this->cs_summary_); this->power_offset_pref_ = global_preferences->make_preference(po_hash, true); this->restore_power_offset_calibrations_(); } else { @@ -183,7 +185,8 @@ void ATM90E32Component::setup() { if (this->enable_gain_calibration_) { // Initialize flash storage for gain calibration - uint32_t g_hash = fnv1_hash(std::string("_gain_calibration_") + this->cs_summary_); + uint32_t g_hash = fnv1_hash("_gain_calibration_"); + g_hash = fnv1_hash_extend(g_hash, this->cs_summary_); this->gain_calibration_pref_ = global_preferences->make_preference(g_hash, true); this->restore_gain_calibrations_(); diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 409c691cb1..d08b52190c 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -395,6 +395,26 @@ constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL; /// FNV-1 32-bit prime constexpr uint32_t FNV1_PRIME = 16777619UL; +/// Extend a FNV-1 hash with an integer (hashes each byte). +template constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) { + for (size_t i = 0; i < sizeof(T); i++) { + hash *= FNV1_PRIME; + hash ^= (value >> (i * 8)) & 0xFF; + } + return hash; +} +/// Extend a FNV-1 hash with additional string data. +constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) { + if (str) { + while (*str) { + hash *= FNV1_PRIME; + hash ^= *str++; + } + } + return hash; +} +inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); } + /// Extend a FNV-1a hash with additional string data. constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) { if (str) {