From 2646ec166baf88fe4ccff5f3896c025d4dcee800 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 15 May 2025 03:24:47 -0500 Subject: [PATCH] save some bytes --- esphome/components/api/api_frame_helper.cpp | 5 +++-- esphome/components/api/api_frame_helper.h | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/esphome/components/api/api_frame_helper.cpp b/esphome/components/api/api_frame_helper.cpp index 82ebd531f6..2d9bed2174 100644 --- a/esphome/components/api/api_frame_helper.cpp +++ b/esphome/components/api/api_frame_helper.cpp @@ -185,9 +185,10 @@ APIError APIFrameHelper::try_send_tx_buf_() { } else if (sent == 0) { // Nothing sent but not an error return APIError::WOULD_BLOCK; - } else if (static_cast(sent) < front_buffer.remaining()) { + } else if (static_cast(sent) < front_buffer.remaining()) { // Partially sent, update offset - front_buffer.offset += sent; + // Cast to ensure no overflow issues with uint16_t + front_buffer.offset += static_cast(sent); return APIError::WOULD_BLOCK; // Stop processing more buffers if we couldn't send a complete buffer } else { // Buffer completely sent, remove it from the queue diff --git a/esphome/components/api/api_frame_helper.h b/esphome/components/api/api_frame_helper.h index 15d9d8664d..f711b091cb 100644 --- a/esphome/components/api/api_frame_helper.h +++ b/esphome/components/api/api_frame_helper.h @@ -121,9 +121,10 @@ class APIFrameHelper { // Buffer containing data to be sent struct SendBuffer { std::vector data; - size_t offset{0}; // Current offset within the buffer + uint16_t offset{0}; // Current offset within the buffer (uint16_t to reduce memory usage) - size_t remaining() const { return data.size() - offset; } + // Using uint16_t reduces memory usage since ESPHome API messages are limited to 64KB max + uint16_t remaining() const { return static_cast(data.size()) - offset; } const uint8_t *current_data() const { return data.data() + offset; } };