mirror of
https://github.com/esphome/esphome.git
synced 2024-11-10 09:17:46 +01:00
Introduce str_snprintf helper function (#2780)
This commit is contained in:
parent
1424091ee5
commit
897277992b
2 changed files with 20 additions and 3 deletions
|
@ -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;
|
||||
|
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in a new issue