diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index a190566bea..0092d202c4 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -351,6 +351,21 @@ 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_sprintf(const char *fmt, ...) { + std::string str; + va_list args; + + va_start(args, fmt); + size_t length = vsnprintf(nullptr, 0, fmt, args); + va_end(args); + + str.resize(length); + va_start(args, fmt); + vsnprintf(&str[0], length + 1, fmt, args); + va_end(args); + + return str; +} uint16_t encode_uint16(uint8_t msb, uint8_t lsb) { return (uint16_t(msb) << 8) | uint16_t(lsb); } std::array decode_uint16(uint16_t value) { diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 8118585db5..f5a7a197ca 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -59,6 +59,9 @@ 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. +std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...); + class HighFrequencyLoopRequester { public: void start();