1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-27 07:32:22 +01:00

Reserve buffer space to avoid frequent realloc when generating protobuf messages (#8707)

This commit is contained in:
J. Nick Koston
2025-05-07 21:56:54 -05:00
committed by GitHub
parent d60e1f02c0
commit 54ead9a6b4
7 changed files with 1705 additions and 7 deletions

View File

@@ -276,6 +276,7 @@ class ProtoMessage {
virtual ~ProtoMessage() = default;
virtual void encode(ProtoWriteBuffer buffer) const = 0;
void decode(const uint8_t *buffer, size_t length);
virtual void calculate_size(uint32_t &total_size) const = 0;
#ifdef HAS_PROTO_MESSAGE_DUMP
std::string dump() const;
virtual void dump_to(std::string &out) const = 0;
@@ -302,9 +303,19 @@ class ProtoService {
virtual bool send_buffer(ProtoWriteBuffer buffer, uint32_t message_type) = 0;
virtual bool read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) = 0;
// Optimized method that pre-allocates buffer based on message size
template<class C> bool send_message_(const C &msg, uint32_t message_type) {
uint32_t msg_size = 0;
msg.calculate_size(msg_size);
// Create a pre-sized buffer
auto buffer = this->create_buffer();
buffer.get_buffer()->reserve(msg_size);
// Encode message into the buffer
msg.encode(buffer);
// Send the buffer
return this->send_buffer(buffer, message_type);
}
};