From 9a028f37ba1d76ca342895c5fb4b0db04809ee39 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 20 Feb 2026 00:02:27 -0600 Subject: [PATCH] [core] Extract base64_decode_quad_ to deduplicate base64 decode logic The base64 character-to-byte conversion was duplicated in both the main decode loop and the tail/padding path. Extract into a shared static helper to reduce flash usage (-64 bytes on ESP32). Co-Authored-By: Claude Opus 4.6 --- esphome/core/helpers.cpp | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index 09e755ca71..4570181617 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -589,10 +589,19 @@ size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf return base64_decode(reinterpret_cast(encoded_string.data()), encoded_string.size(), buf, buf_len); } +// Convert 4 base64 characters to 3 decoded bytes +static inline void base64_decode_quad_(uint8_t *char_array_4, uint8_t *char_array_3) { + for (int i = 0; i < 4; i++) + char_array_4[i] = base64_find_char(char_array_4[i]); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; +} + size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len) { size_t in_len = encoded_len; int i = 0; - int j = 0; size_t in = 0; size_t out = 0; uint8_t char_array_4[4], char_array_3[3]; @@ -605,12 +614,7 @@ size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *b char_array_4[i++] = encoded_data[in]; in++; if (i == 4) { - for (i = 0; i < 4; i++) - char_array_4[i] = base64_find_char(char_array_4[i]); - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + base64_decode_quad_(char_array_4, char_array_3); for (i = 0; i < 3; i++) { if (out < buf_len) { @@ -624,17 +628,12 @@ size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *b } if (i) { - for (j = i; j < 4; j++) + for (int j = i; j < 4; j++) char_array_4[j] = 0; - for (j = 0; j < 4; j++) - char_array_4[j] = base64_find_char(char_array_4[j]); + base64_decode_quad_(char_array_4, char_array_3); - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (j = 0; j < i - 1; j++) { + for (int j = 0; j < i - 1; j++) { if (out < buf_len) { buf[out++] = char_array_3[j]; } else {