save some more

This commit is contained in:
J. Nick Koston 2025-07-19 13:43:47 -10:00
parent 2ca306c1c1
commit b125cd6979
No known key found for this signature in database
2 changed files with 12 additions and 7 deletions

View File

@ -80,8 +80,11 @@ APIError APIFrameHelper::loop() {
void APIFrameHelper::buffer_data_from_iov_(const struct iovec *iov, int iovcnt, uint16_t total_write_len,
uint16_t offset) {
SendBuffer buffer;
buffer.data.reserve(total_write_len - offset);
buffer.size = total_write_len - offset;
buffer.data = std::make_unique<uint8_t[]>(buffer.size);
uint16_t to_skip = offset;
uint16_t write_pos = 0;
for (int i = 0; i < iovcnt; i++) {
if (to_skip >= iov[i].iov_len) {
@ -89,9 +92,10 @@ void APIFrameHelper::buffer_data_from_iov_(const struct iovec *iov, int iovcnt,
to_skip -= static_cast<uint16_t>(iov[i].iov_len);
} else {
// Include this segment (partially or fully)
const uint8_t *data = reinterpret_cast<uint8_t *>(iov[i].iov_base) + to_skip;
const uint8_t *src = reinterpret_cast<uint8_t *>(iov[i].iov_base) + to_skip;
uint16_t len = static_cast<uint16_t>(iov[i].iov_len) - to_skip;
buffer.data.insert(buffer.data.end(), data, data + len);
std::memcpy(buffer.data.get() + write_pos, src, len);
write_pos += len;
to_skip = 0;
}
}

View File

@ -116,12 +116,13 @@ class APIFrameHelper {
// Buffer containing data to be sent
struct SendBuffer {
std::vector<uint8_t> data;
uint16_t offset{0}; // Current offset within the buffer (uint16_t to reduce memory usage)
std::unique_ptr<uint8_t[]> data;
uint16_t size{0}; // Total size of the buffer
uint16_t offset{0}; // Current offset within the buffer
// Using uint16_t reduces memory usage since ESPHome API messages are limited to UINT16_MAX (65535) bytes
uint16_t remaining() const { return static_cast<uint16_t>(data.size()) - offset; }
const uint8_t *current_data() const { return data.data() + offset; }
uint16_t remaining() const { return size - offset; }
const uint8_t *current_data() const { return data.get() + offset; }
};
// Common implementation for writing raw data to socket