From a3553dab1ccdc2e1d1de80a77c7f96c3de8b2566 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 8 Jan 2026 22:24:38 -1000 Subject: [PATCH] address copilot review comments --- esphome/components/fan/fan.cpp | 4 +++- esphome/components/fan/fan.h | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/esphome/components/fan/fan.cpp b/esphome/components/fan/fan.cpp index 3c1e1357f55..79301a2e182 100644 --- a/esphome/components/fan/fan.cpp +++ b/esphome/components/fan/fan.cpp @@ -156,7 +156,7 @@ const char *Fan::find_preset_mode_(const char *preset_mode, size_t len) { bool Fan::set_preset_mode_(const char *preset_mode, size_t len) { if (preset_mode == nullptr || len == 0) { - // Treat nullptr/empty as clearing the preset mode + // Treat nullptr or empty string as clearing the preset mode (no valid preset is "") if (this->preset_mode_ == nullptr) { return false; // No change } @@ -180,6 +180,8 @@ bool Fan::set_preset_mode_(const std::string &preset_mode) { } bool Fan::set_preset_mode_(std::string_view preset_mode) { + // Safe: find_preset_mode_ only uses the input for comparison and returns + // a pointer from traits, so the input string_view's lifetime doesn't matter. return this->set_preset_mode_(preset_mode.data(), preset_mode.size()); } diff --git a/esphome/components/fan/fan.h b/esphome/components/fan/fan.h index df42af9f996..c16ec389f20 100644 --- a/esphome/components/fan/fan.h +++ b/esphome/components/fan/fan.h @@ -131,8 +131,9 @@ class Fan : public EntityBase { void set_restore_mode(FanRestoreMode restore_mode) { this->restore_mode_ = restore_mode; } /// Get the current preset mode. - /// Returns a view of the string stored in traits (static storage), or empty view if not set. - /// Safe to use as the underlying string has static lifetime. + /// Returns a view of the string stored in traits, or empty view if not set. + /// The returned view points to string literals from codegen (static storage). + /// Traits are set once at startup and valid for the lifetime of the program. std::string_view get_preset_mode() const { return this->preset_mode_ != nullptr ? std::string_view(this->preset_mode_) : std::string_view(); }