diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index 3e614eb515..37d9cdc24b 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -48,13 +48,13 @@ void get_mac_address_raw(uint8_t *mac) { std::string get_mac_address() { uint8_t mac[6]; get_mac_address_raw(mac); - return str_sprintf("%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return str_snprintf("%02x%02x%02x%02x%02x%02x", 12, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); } std::string get_mac_address_pretty() { uint8_t mac[6]; get_mac_address_raw(mac); - return str_sprintf("%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return str_snprintf("%02X:%02X:%02X:%02X:%02X:%02X", 17, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); } #ifdef USE_ESP32 @@ -325,6 +325,20 @@ bool str_startswith(const std::string &full, const std::string &start) { return bool str_endswith(const std::string &full, const std::string &ending) { return full.rfind(ending) == (full.size() - ending.size()); } +std::string str_snprintf(const char *fmt, size_t length, ...) { + std::string str; + va_list args; + + str.resize(length); + va_start(args, length); + size_t out_length = vsnprintf(&str[0], length + 1, fmt, args); + va_end(args); + + if (out_length < length) + str.resize(out_length); + + return str; +} std::string str_sprintf(const char *fmt, ...) { std::string str; va_list args; diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 120642c62e..4ce1f08074 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -57,7 +57,10 @@ bool str_equals_case_insensitive(const std::string &a, const std::string &b); bool str_startswith(const std::string &full, const std::string &start); bool str_endswith(const std::string &full, const std::string &ending); -/// sprintf-like function returning std::string instead of writing to char array. +/// snprintf-like function returning std::string with a given maximum length. +std::string __attribute__((format(printf, 1, 3))) str_snprintf(const char *fmt, size_t length, ...); + +/// sprintf-like function returning std::string. std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...); class HighFrequencyLoopRequester {