From cbafc19bec472022f9154fd203c05b4f8d840ed1 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 28 May 2025 09:36:42 -0500 Subject: [PATCH] set not needed --- esphome/core/application.cpp | 27 +++++++++++++++++++-------- esphome/core/application.h | 3 +-- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/esphome/core/application.cpp b/esphome/core/application.cpp index 87b4f2eb97..1cc96265ab 100644 --- a/esphome/core/application.cpp +++ b/esphome/core/application.cpp @@ -2,6 +2,7 @@ #include "esphome/core/log.h" #include "esphome/core/version.h" #include "esphome/core/hal.h" +#include #ifdef USE_STATUS_LED #include "esphome/components/status_led/status_led.h" @@ -256,7 +257,7 @@ bool Application::register_socket_fd(int fd) { return false; } - this->socket_fds_.insert(fd); + this->socket_fds_.push_back(fd); this->socket_fds_changed_ = true; if (fd > this->max_fd_) { @@ -272,14 +273,24 @@ void Application::unregister_socket_fd(int fd) { if (fd < 0) return; - this->socket_fds_.erase(fd); - this->socket_fds_changed_ = true; + auto it = std::find(this->socket_fds_.begin(), this->socket_fds_.end(), fd); + if (it != this->socket_fds_.end()) { + // Swap with last element and pop - O(1) removal since order doesn't matter + if (it != this->socket_fds_.end() - 1) { + std::swap(*it, this->socket_fds_.back()); + } + this->socket_fds_.pop_back(); + this->socket_fds_changed_ = true; - // Recalculate max_fd if necessary - if (fd == this->max_fd_ && !this->socket_fds_.empty()) { - this->max_fd_ = *this->socket_fds_.rbegin(); - } else if (this->socket_fds_.empty()) { - this->max_fd_ = -1; + // Only recalculate max_fd if we removed the current max + if (fd == this->max_fd_) { + if (this->socket_fds_.empty()) { + this->max_fd_ = -1; + } else { + // Find new max using std::max_element + this->max_fd_ = *std::max_element(this->socket_fds_.begin(), this->socket_fds_.end()); + } + } } } diff --git a/esphome/core/application.h b/esphome/core/application.h index 6236bf8f76..c0247282af 100644 --- a/esphome/core/application.h +++ b/esphome/core/application.h @@ -2,7 +2,6 @@ #include #include -#include #include "esphome/core/component.h" #include "esphome/core/defines.h" #include "esphome/core/hal.h" @@ -576,7 +575,7 @@ class Application { #ifdef USE_SOCKET_SELECT_SUPPORT // Socket select management - std::set socket_fds_; // Set of all monitored socket file descriptors + std::vector socket_fds_; // Vector of all monitored socket file descriptors bool socket_fds_changed_{false}; // Flag to rebuild base_read_fds_ when socket_fds_ changes int max_fd_{-1}; // Highest file descriptor number for select() fd_set base_read_fds_{}; // Cached fd_set rebuilt only when socket_fds_ changes