mirror of
https://github.com/esphome/esphome.git
synced 2026-10-06 10:56:43 +00:00
[sun] Eliminate heap allocation in text sensor (#13037)
This commit is contained in:
+16
-7
@@ -1,6 +1,7 @@
|
||||
#include "time.h" // NOLINT
|
||||
#include "helpers.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
|
||||
namespace esphome {
|
||||
@@ -17,6 +18,18 @@ size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) {
|
||||
return ::strftime(buffer, buffer_len, format, &c_tm);
|
||||
}
|
||||
|
||||
size_t ESPTime::strftime_to(std::span<char, STRFTIME_BUFFER_SIZE> buffer, const char *format) {
|
||||
struct tm c_tm = this->to_c_tm();
|
||||
size_t len = ::strftime(buffer.data(), buffer.size(), format, &c_tm);
|
||||
if (len > 0) {
|
||||
return len;
|
||||
}
|
||||
// Write "ERROR" to buffer on failure for consistent behavior
|
||||
constexpr char error_str[] = "ERROR";
|
||||
std::copy_n(error_str, sizeof(error_str), buffer.data());
|
||||
return sizeof(error_str) - 1; // Length excluding null terminator
|
||||
}
|
||||
|
||||
ESPTime ESPTime::from_c_tm(struct tm *c_tm, time_t c_time) {
|
||||
ESPTime res{};
|
||||
res.second = uint8_t(c_tm->tm_sec);
|
||||
@@ -47,13 +60,9 @@ struct tm ESPTime::to_c_tm() {
|
||||
}
|
||||
|
||||
std::string ESPTime::strftime(const char *format) {
|
||||
struct tm c_tm = this->to_c_tm();
|
||||
char buf[128];
|
||||
size_t len = ::strftime(buf, sizeof(buf), format, &c_tm);
|
||||
if (len > 0) {
|
||||
return std::string(buf, len);
|
||||
}
|
||||
return "ERROR";
|
||||
char buf[STRFTIME_BUFFER_SIZE];
|
||||
size_t len = this->strftime_to(buf, format);
|
||||
return std::string(buf, len);
|
||||
}
|
||||
|
||||
std::string ESPTime::strftime(const std::string &format) { return this->strftime(format.c_str()); }
|
||||
|
||||
Reference in New Issue
Block a user