ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
helpers.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <array>
5#include <cassert>
6#include <cmath>
7#include <cstdarg>
8#include <cstddef>
9#include <cstdint>
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <functional>
14#include <iterator>
15#include <limits>
16#include <memory>
17#include <new>
18#include <numeric>
19#include <span>
20#include <string>
21#include <type_traits>
22#include <utility>
23#include <vector>
24#include <concepts>
25#include <strings.h>
26
29
30#ifdef USE_ESP8266
31#include <Esp.h>
32#include <core_esp8266_features.h> // xt_rsil, xt_wsr_ps
33#include <pgmspace.h>
34#endif
35
36#ifdef USE_RP2
37#include <Arduino.h>
38#endif
39
40#ifdef USE_ESP32
41#include <esp_system.h>
42#include <esp_heap_caps.h>
43#endif
44
45#if defined(USE_ESP32)
46#include <freertos/FreeRTOS.h>
47#include <freertos/semphr.h>
48#elif defined(USE_LIBRETINY)
49#include <FreeRTOS.h>
50#include <semphr.h>
51#endif
52
53#ifdef USE_HOST
54#include <mutex>
55#endif
56
57#define HOT __attribute__((hot))
58#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
59#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
60#define PACKED __attribute__((packed))
61
62namespace esphome {
63
64// Forward declaration to avoid circular dependency with string_ref.h
65class StringRef;
66
69
70// Keep "using" even after the removal of our backports, to avoid breaking existing code.
71using std::to_string;
72using std::is_trivially_copyable;
73using std::make_unique;
74using std::enable_if_t;
75using std::clamp;
76using std::is_invocable;
77#if __cpp_lib_bit_cast >= 201806
78using std::bit_cast;
79#else
81template<
82 typename To, typename From,
83 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
84 int> = 0>
85To bit_cast(const From &src) {
86 To dst;
87 memcpy(&dst, &src, sizeof(To));
88 return dst;
89}
90#endif
91
92// clang-format off
93inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
94// clang-format on
95
96// std::byteswap from C++23
97template<typename T> constexpr T byteswap(T n) {
98 T m;
99 for (size_t i = 0; i < sizeof(T); i++)
100 reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
101 return m;
102}
103template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
104#ifdef USE_LIBRETINY
105// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
106template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
107template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
108template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
109template<> inline int8_t byteswap(int8_t n) { return n; }
110template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
111template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
112template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
113#else
114template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
115template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
116template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
117template<> constexpr int8_t byteswap(int8_t n) { return n; }
118template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
119template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
120template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
121#endif
122
124
127
131template<typename T, bool Owning = false> class ConstVector {
132 public:
133 using value_type = T;
134
135 constexpr ConstVector() = default;
136 constexpr ConstVector(const T *data, size_t size) : data_(data), size_(size) {}
137
138 const T *begin() const { return this->data_; }
139 const T *end() const { return this->data_ + this->size_; }
140 const T *data() const { return this->data_; }
141 constexpr size_t size() const { return this->size_; }
142 constexpr bool empty() const { return this->size_ == 0; }
143 const constexpr T &operator[](size_t i) const { return this->data_[i]; }
144 const T &at(size_t i) const { return this->data_[i]; }
145
146 protected:
147 const T *data_{nullptr};
148 size_t size_{0};
149};
150
154template<typename T> class ConstVector<T, true> {
155 static_assert(std::is_trivially_copyable_v<T> && sizeof(T) % sizeof(uint32_t) == 0,
156 "ConstVector elements must be whole words so ESP8266 can index them in flash");
157
158 public:
159 using value_type = T;
160
161 constexpr ConstVector() = default;
162 constexpr ConstVector(const T *data, size_t size) : data_(data), size_(size) {}
163 ConstVector(const ConstVector &) = delete;
165 ~ConstVector() { this->release_(); }
166
167 const T *begin() const { return this->data_; }
168 const T *end() const { return this->data_ + this->size(); }
169 const T *data() const { return this->data_; }
170 size_t size() const { return this->size_ & ~OWNED_BIT; }
171 bool empty() const { return this->size() == 0; }
172 const T &operator[](size_t index) const { return this->data_[index]; }
173 const T &at(size_t index) const { return this->data_[index]; }
174
177 void assign_static(const T *data, size_t size) {
178 this->data_ = data;
179 this->size_ = size;
180 }
183 void append_copy(const T *extra, size_t count) { this->merge_copy_(this->data_, this->size(), extra, count); }
185 void prepend_copy(const T *extra, size_t count) { this->merge_copy_(extra, count, this->data_, this->size()); }
187 void assign_copy(const T *data, size_t size) { this->merge_copy_(data, size, nullptr, 0); }
188
189 protected:
190 static constexpr size_t OWNED_BIT = size_t{1} << (sizeof(size_t) * 8 - 1);
191
192 void release_() {
193 if (this->size_ & OWNED_BIT)
194 delete[] this->data_; // NOLINT(cppcoreguidelines-owning-memory)
195 }
196 void merge_copy_(const T *first, size_t first_count, const T *second, size_t second_count) {
197 auto *table = new T[first_count + second_count]; // NOLINT(cppcoreguidelines-owning-memory)
198 copy_items(first, first_count, table);
199 copy_items(second, second_count, table + first_count);
200 this->release_(); // after the copies: first or second may be the current list
201 this->data_ = table;
202 this->size_ = (first_count + second_count) | OWNED_BIT;
203 }
204 // ESP8266: the source may be a table in flash
205 static void copy_items(const T *src, size_t count, T *dst) {
206 if (count == 0)
207 return;
208#ifdef USE_ESP8266
209 memcpy_P(dst, src, count * sizeof(T));
210#else
211 std::copy(src, src + count, dst);
212#endif
213 }
214
215 const T *data_{nullptr};
216 size_t size_{0}; // top bit set when data_ is an owned heap copy
217};
218static_assert(sizeof(ConstVector<const char *, true>) == 2 * sizeof(void *),
219 "ConstVector must stay a pointer and a size");
220
224template<size_t InlineSize = 8> class SmallInlineBuffer {
225 public:
226 SmallInlineBuffer() = default;
228 if (!this->is_inline_())
229 delete[] this->heap_;
230 }
231
232 // Move constructor
233 SmallInlineBuffer(SmallInlineBuffer &&other) noexcept : len_(other.len_) {
234 if (other.is_inline_()) {
235 memcpy(this->inline_, other.inline_, this->len_);
236 } else {
237 this->heap_ = other.heap_;
238 other.heap_ = nullptr;
239 }
240 other.len_ = 0;
241 }
242
243 // Move assignment
245 if (this != &other) {
246 if (!this->is_inline_())
247 delete[] this->heap_;
248 this->len_ = other.len_;
249 if (other.is_inline_()) {
250 memcpy(this->inline_, other.inline_, this->len_);
251 } else {
252 this->heap_ = other.heap_;
253 other.heap_ = nullptr;
254 }
255 other.len_ = 0;
256 }
257 return *this;
258 }
259
260 // Disable copy (would need deep copy of heap data)
263
264 bool empty() const { return this->len_ == 0; }
265
266 // Conversion to std::span for compatibility with span-based APIs
267 operator std::span<const uint8_t>() const { return std::span<const uint8_t>(this->data(), this->len_); }
268
272 uint8_t *init(size_t size) {
273 // Free existing heap allocation if switching from heap to inline or different heap size
275 delete[] this->heap_;
276 this->heap_ = nullptr; // Defensive: prevent use-after-free if logic changes
277 }
278 // Allocate new heap buffer if needed
279 if (size > InlineSize && (this->is_inline_() || size != this->len_)) {
280 this->heap_ = new uint8_t[size]; // NOLINT(cppcoreguidelines-owning-memory)
281 }
282 this->len_ = size;
283 return this->data();
284 }
285
287 void set(const uint8_t *src, size_t size) { memcpy(this->init(size), src, size); }
288
289 uint8_t *data() { return this->is_inline_() ? this->inline_ : this->heap_; }
290 const uint8_t *data() const { return this->is_inline_() ? this->inline_ : this->heap_; }
291 size_t size() const { return this->len_; }
292
293 protected:
294 bool is_inline_() const { return this->len_ <= InlineSize; }
295
296 size_t len_{0};
297 union {
298 uint8_t inline_[InlineSize]{}; // Zero-init ensures clean initial state
299 uint8_t *heap_;
300 };
301};
302
304template<typename T, size_t N> class StaticVector {
305 public:
306 using value_type = T;
307 using iterator = typename std::array<T, N>::iterator;
308 using const_iterator = typename std::array<T, N>::const_iterator;
309 using reverse_iterator = std::reverse_iterator<iterator>;
310 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
311
312 private:
313 std::array<T, N> data_; // intentionally not value-initialized to avoid memset
314 size_t count_{0};
315
316 public:
317 // User provided, not "= default": otherwise `StaticVector<...> x_{}` members
318 // value-initialize and memset data_, defeating the comment above.
319 constexpr StaticVector() noexcept {}
320
321 // Iterator range constructor
322 template<typename InputIt> StaticVector(InputIt first, InputIt last) {
323 while (first != last && count_ < N) {
324 data_[count_++] = *first++;
325 }
326 }
327
328 // Initializer list constructor
329 StaticVector(std::initializer_list<T> init) {
330 for (const auto &val : init) {
331 if (count_ >= N)
332 break;
333 data_[count_++] = val;
334 }
335 }
336
337 // Converting constructor from a smaller StaticVector of the same element type
338 template<size_t M> StaticVector(const StaticVector<T, M> &other) : StaticVector(other.begin(), other.end()) {
339 static_assert(M <= N, "Source StaticVector cannot be larger than the destination");
340 }
341
342 // Minimal vector-compatible interface - only what we actually use
343 void push_back(const T &value) {
344 if (count_ < N) {
345 data_[count_++] = value;
346 }
347 }
348
349 // Clear all elements
350 void clear() { count_ = 0; }
351 // Set the element count, capped at N. Elements are neither initialized when growing nor destroyed when
352 // shrinking; release owning elements before shrinking past them.
353 void resize(size_t n) { count_ = n < N ? n : N; }
354
355 // Assign from iterator range
356 template<typename InputIt> void assign(InputIt first, InputIt last) {
357 count_ = 0;
358 while (first != last && count_ < N) {
359 data_[count_++] = *first++;
360 }
361 }
362
363 // Return reference to next element and increment count (with bounds checking)
365 if (count_ >= N) {
366 // Should never happen with proper size calculation
367 // Return reference to last element to avoid crash
368 return data_[N - 1];
369 }
370 return data_[count_++];
371 }
372
373 size_t size() const { return count_; }
374 static constexpr size_t capacity() { return N; }
375 bool empty() const { return count_ == 0; }
376
377 // Direct access to underlying data
378 T *data() { return data_.data(); }
379 const T *data() const { return data_.data(); }
380
381 T &operator[](size_t i) { return data_[i]; }
382 const T &operator[](size_t i) const { return data_[i]; }
383
384 // For range-based for loops
385 iterator begin() { return data_.begin(); }
386 iterator end() { return data_.begin() + count_; }
387 const_iterator begin() const { return data_.begin(); }
388 const_iterator end() const { return data_.begin() + count_; }
389
390 // Reverse iterators
395
396 // Conversion to std::span for compatibility with span-based APIs
397 operator std::span<T>() { return std::span<T>(data_.data(), count_); }
398 operator std::span<const T>() const { return std::span<const T>(data_.data(), count_); }
399};
400
408template<typename T, size_t N> class StaticRingBuffer {
409 using index_type = std::conditional_t<(N <= std::numeric_limits<uint8_t>::max()), uint8_t, uint16_t>;
410
411 public:
412 class Iterator {
413 public:
414 Iterator(StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
415 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % N]; }
417 ++pos_;
418 return *this;
419 }
420 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
421
422 private:
423 StaticRingBuffer *buf_;
424 index_type pos_;
425 };
426
428 public:
429 ConstIterator(const StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
430 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % N]; }
432 ++pos_;
433 return *this;
434 }
435 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
436
437 private:
438 const StaticRingBuffer *buf_;
439 index_type pos_;
440 };
441
442 bool push(const T &value) {
443 if (this->count_ >= N) {
444 return false;
445 }
446 this->data_[this->tail_] = value;
447 this->tail_ = (this->tail_ + 1) % N;
448 ++this->count_;
449 return true;
450 }
451
452 void pop() {
453 if (this->count_ > 0) {
454 this->head_ = (this->head_ + 1) % N;
455 --this->count_;
456 }
457 }
458
459 T &front() { return this->data_[this->head_]; }
460 const T &front() const { return this->data_[this->head_]; }
461 index_type size() const { return this->count_; }
462 bool empty() const { return this->count_ == 0; }
463
465 void clear() {
466 this->head_ = 0;
467 this->tail_ = 0;
468 this->count_ = 0;
469 }
470
471 Iterator begin() { return Iterator(this, 0); }
472 Iterator end() { return Iterator(this, this->count_); }
473 ConstIterator begin() const { return ConstIterator(this, 0); }
474 ConstIterator end() const { return ConstIterator(this, this->count_); }
475
476 protected:
477 T data_[N];
478 index_type head_{0};
479 index_type tail_{0};
480 index_type count_{0};
481};
482
487template<typename T, size_t MAX_CAPACITY = std::numeric_limits<uint16_t>::max()> class FixedRingBuffer {
488 using index_type = std::conditional_t<
489 (MAX_CAPACITY <= std::numeric_limits<uint8_t>::max()), uint8_t,
490 std::conditional_t<(MAX_CAPACITY <= std::numeric_limits<uint16_t>::max()), uint16_t, uint32_t>>;
491
492 public:
493 class Iterator {
494 public:
495 Iterator(FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
496 T &operator*() { return buf_->data_[buf_->wrap_(static_cast<size_t>(buf_->head_) + pos_)]; }
498 ++pos_;
499 return *this;
500 }
501 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
502
503 private:
504 FixedRingBuffer *buf_;
505 index_type pos_;
506 };
507
509 public:
510 ConstIterator(const FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
511 const T &operator*() const { return buf_->data_[buf_->wrap_(static_cast<size_t>(buf_->head_) + pos_)]; }
513 ++pos_;
514 return *this;
515 }
516 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
517
518 private:
519 const FixedRingBuffer *buf_;
520 index_type pos_;
521 };
522
523 FixedRingBuffer() = default;
525 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
526 ::operator delete(this->data_);
527 } else {
528 delete[] this->data_;
529 }
530 }
531
532 // Disable copy
535
537 void init(index_type capacity) {
538 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
539 // Raw allocation without initialization (elements are written before read)
540 // NOLINTNEXTLINE(bugprone-sizeof-expression)
541 this->data_ = static_cast<T *>(::operator new(capacity * sizeof(T)));
542 } else {
543 this->data_ = new T[capacity];
544 }
545 this->capacity_ = capacity;
546 }
547
549 bool push(const T &value) {
550 if (this->count_ >= this->capacity_)
551 return false;
552 this->data_[this->tail_] = value;
553 this->tail_ = this->wrap_(static_cast<size_t>(this->tail_) + 1);
554 ++this->count_;
555 return true;
556 }
557
559 void push_overwrite(const T &value) {
560 this->data_[this->tail_] = value;
561 this->tail_ = this->wrap_(static_cast<size_t>(this->tail_) + 1);
562 if (this->count_ >= this->capacity_) {
563 // Buffer full - advance head to drop oldest, count stays at capacity
564 this->head_ = this->tail_;
565 } else {
566 ++this->count_;
567 }
568 }
569
571 size_t push(const T *data, size_t len) {
572 static_assert(std::is_trivially_copyable<T>::value, "bulk push copies with memcpy");
573 len = std::min<size_t>(len, this->free_space());
574 if (len == 0)
575 return 0; // data_ may be null, and memcpy with a null pointer is undefined even for 0 bytes
576 const size_t first = std::min<size_t>(len, this->capacity_ - this->tail_);
577 std::memcpy(this->data_ + this->tail_, data, first * sizeof(T));
578 std::memcpy(this->data_, data + first, (len - first) * sizeof(T));
579 this->tail_ = this->wrap_(static_cast<size_t>(this->tail_) + len);
580 this->count_ += len;
581 return len;
582 }
583
585 void pop() {
586 if (this->count_ > 0) {
587 this->head_ = this->wrap_(static_cast<size_t>(this->head_) + 1);
588 --this->count_;
589 }
590 }
591
593 size_t pop(T *out, size_t len) {
594 static_assert(std::is_trivially_copyable<T>::value, "bulk pop copies with memcpy");
595 len = std::min<size_t>(len, this->count_);
596 if (len == 0)
597 return 0;
598 const size_t first = std::min<size_t>(len, this->capacity_ - this->head_);
599 std::memcpy(out, this->data_ + this->head_, first * sizeof(T));
600 std::memcpy(out + first, this->data_, (len - first) * sizeof(T));
601 this->head_ = this->wrap_(static_cast<size_t>(this->head_) + len);
602 this->count_ -= len;
603 return len;
604 }
605
606 T &front() { return this->data_[this->head_]; }
607 const T &front() const { return this->data_[this->head_]; }
608 index_type size() const { return this->count_; }
609 bool empty() const { return this->count_ == 0; }
610 index_type capacity() const { return this->capacity_; }
611 index_type free_space() const { return this->capacity_ - this->count_; }
612 bool full() const { return this->count_ == this->capacity_; }
613
615 void clear() {
616 this->head_ = 0;
617 this->tail_ = 0;
618 this->count_ = 0;
619 }
620
621 Iterator begin() { return Iterator(this, 0); }
622 Iterator end() { return Iterator(this, this->count_); }
623 ConstIterator begin() const { return ConstIterator(this, 0); }
624 ConstIterator end() const { return ConstIterator(this, this->count_); }
625
627 const T &operator[](index_type pos) const { return this->data_[this->wrap_(static_cast<size_t>(this->head_) + pos)]; }
628
629 protected:
631 index_type wrap_(size_t index) const { return index >= this->capacity_ ? index - this->capacity_ : index; }
632
633 T *data_{nullptr};
634 index_type head_{0};
635 index_type tail_{0};
636 index_type count_{0};
637 index_type capacity_{0};
638};
639
644template<typename T, size_t N> inline void init_array_from(std::array<T, N> &dest, std::initializer_list<T> src) {
645#ifdef ESPHOME_DEBUG
646 assert(src.size() == N);
647#endif
648 if constexpr (std::is_trivially_copyable_v<T>) {
649 __builtin_memcpy(dest.data(), src.begin(), N * sizeof(T));
650 } else {
651 size_t i = 0;
652 for (const auto &v : src) {
653 dest[i++] = v;
654 }
655 }
656}
657
658// Abort with a reason that reaches the panic output on ESP32. Elsewhere the literal is dropped
659// before it can land in rodata, which is RAM on ESP8266
660#ifdef USE_ESP32
661#define ESPHOME_ABORT_WITH_REASON(reason) esp_system_abort(reason)
662#else
663#define ESPHOME_ABORT_WITH_REASON(reason) abort()
664#endif
665
669template<typename T> class FixedVector {
670 private:
671 T *data_{nullptr};
672 size_t size_{0};
673 size_t capacity_{0};
674
675 // Helper to destroy all elements without freeing memory
676 void destroy_elements_() {
677 // Only call destructors for non-trivially destructible types
678 if constexpr (!std::is_trivially_destructible<T>::value) {
679 for (size_t i = 0; i < size_; i++) {
680 data_[i].~T();
681 }
682 }
683 }
684
685 // Helper to destroy elements and free memory
686 void cleanup_() {
687 if (data_ != nullptr) {
688 destroy_elements_();
689 free(data_); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
690 }
691 }
692
693 // Helper to reset pointers after cleanup
694 void reset_() {
695 data_ = nullptr;
696 capacity_ = 0;
697 size_ = 0;
698 }
699
700 // Helper to assign from initializer list (shared by constructor and assignment operator)
701 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
702 init(init_list.size());
703 size_t idx = 0;
704 for (const auto &item : init_list) {
705 new (data_ + idx) T(item);
706 ++idx;
707 }
708 size_ = init_list.size();
709 }
710
711 public:
712 FixedVector() = default;
713
716 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
717
718 ~FixedVector() { cleanup_(); }
719
720 // Disable copy operations (avoid accidental expensive copies)
721 FixedVector(const FixedVector &) = delete;
723
724 // Enable move semantics (allows use in move-only containers like std::vector)
725 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
726 other.reset_();
727 }
728
729 // Allow conversion to std::vector
730 operator std::vector<T>() const { return {data_, data_ + size_}; }
731
732 FixedVector &operator=(FixedVector &&other) noexcept {
733 if (this != &other) {
734 // Delete our current data
735 cleanup_();
736 // Take ownership of other's data
737 data_ = other.data_;
738 size_ = other.size_;
739 capacity_ = other.capacity_;
740 // Leave other in valid empty state
741 other.reset_();
742 }
743 return *this;
744 }
745
748 FixedVector &operator=(std::initializer_list<T> init_list) {
749 cleanup_();
750 reset_();
751 assign_from_initializer_list_(init_list);
752 return *this;
753 }
754
755 // Allocate capacity - can be called multiple times to reinit
756 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
757 // Direct assignment via operator[] does NOT update the size counter.
758 // Aborts on exhaustion; use try_init() to handle failure.
759 void init(size_t n) {
760 if (!try_init(n))
761 ESPHOME_ABORT_WITH_REASON("FixedVector: out of memory");
762 }
763
764 // Same as init(), but returns false when memory is exhausted; the previous storage is freed either way
765 bool try_init(size_t n) {
766 cleanup_();
767 reset_();
768 if (n == 0)
769 return true;
770 if (n > SIZE_MAX / sizeof(T))
771 return false; // the byte count would wrap into a small block
772 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
773 // NOLINTNEXTLINE(bugprone-sizeof-expression,cppcoreguidelines-no-malloc,cppcoreguidelines-owning-memory)
774 data_ = static_cast<T *>(malloc(n * sizeof(T)));
775 if (data_ == nullptr)
776 return false;
777 capacity_ = n;
778 return true;
779 }
780
781 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
782 void clear() {
783 destroy_elements_();
784 size_ = 0;
785 }
786
787 // Release all memory (destroys elements and frees memory)
788 void release() {
789 cleanup_();
790 reset_();
791 }
792
796 void push_back(const T &value) {
797 if (size_ < capacity_) {
798 // Use placement new to construct the object in pre-allocated memory
799 new (&data_[size_]) T(value);
800 size_++;
801 }
802 }
803
807 void push_back(T &&value) {
808 if (size_ < capacity_) {
809 // Use placement new to move-construct the object in pre-allocated memory
810 new (&data_[size_]) T(std::move(value));
811 size_++;
812 }
813 }
814
819 template<typename... Args> T &emplace_back(Args &&...args) {
820 // Use placement new to construct the object in pre-allocated memory
821 new (&data_[size_]) T(std::forward<Args>(args)...);
822 size_++;
823 return data_[size_ - 1];
824 }
825
828 T &front() { return data_[0]; }
829 const T &front() const { return data_[0]; }
830
833 T &back() { return data_[size_ - 1]; }
834 const T &back() const { return data_[size_ - 1]; }
835
838 void pop_back() {
839 if constexpr (!std::is_trivially_destructible<T>::value) {
840 data_[size_ - 1].~T();
841 }
842 size_--;
843 }
844
845 size_t size() const { return size_; }
846 bool empty() const { return size_ == 0; }
847 size_t capacity() const { return capacity_; }
848 bool full() const { return size_ == capacity_; }
849
852 T &operator[](size_t i) { return data_[i]; }
853 const T &operator[](size_t i) const { return data_[i]; }
854
857 T &at(size_t i) { return data_[i]; }
858 const T &at(size_t i) const { return data_[i]; }
859
860 // Iterator support for range-based for loops
861 T *begin() { return data_; }
862 T *end() { return data_ + size_; }
863 const T *begin() const { return data_; }
864 const T *end() const { return data_ + size_; }
865};
866
872template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
873 public:
875 static_assert(std::is_trivially_default_constructible_v<T> && std::is_trivially_destructible_v<T>,
876 "the heap fallback leaves elements unconstructed");
877 if (size <= STACK_SIZE) {
878 this->buffer_ = this->stack_buffer_;
879 } else {
880 if (size <= SIZE_MAX / sizeof(T)) {
881 // NOLINTNEXTLINE(bugprone-sizeof-expression,cppcoreguidelines-no-malloc,cppcoreguidelines-owning-memory)
882 this->heap_buffer_ = static_cast<T *>(malloc(size * sizeof(T)));
883 }
884 // Callers write through get() unchecked, so exhaustion aborts like the new[] it replaces
885 if (this->heap_buffer_ == nullptr)
886 ESPHOME_ABORT_WITH_REASON("SmallBufferWithHeapFallback: out of memory");
887 this->buffer_ = this->heap_buffer_;
888 }
889 }
890 ~SmallBufferWithHeapFallback() { free(this->heap_buffer_); } // NOLINT(cppcoreguidelines-no-malloc)
891
892 // Delete copy and move operations to prevent double-delete
897
898 T *get() { return this->buffer_; }
899
900 private:
901 T stack_buffer_[STACK_SIZE];
902 T *heap_buffer_{nullptr};
903 T *buffer_;
904};
905
907
910
914int8_t ilog10(float value);
915
919inline float pow10_int(int8_t exp) {
920 float result = 1.0f;
921 if (exp >= 0) {
922 for (int8_t i = 0; i < exp; i++)
923 result *= 10.0f;
924 } else {
925 for (int8_t i = exp; i < 0; i++)
926 result /= 10.0f;
927 }
928 return result;
929}
930
932template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
933 return (value - min) * (max_out - min_out) / (max - min) + min_out;
934}
935
939constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum = 0) {
940 return std::accumulate(data, data + len, sum);
941}
942
944constexpr uint16_t sum16_bytes(const uint8_t *data, size_t len, uint16_t sum = 0) {
945 return std::accumulate(data, data + len, sum);
946}
947
949constexpr uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init = 0) {
950 return std::accumulate(data, data + len, init, std::bit_xor<>());
951}
952
954uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
955
957uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
958 bool refin = false, bool refout = false);
959uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
960 bool refout = false);
961
964uint32_t fnv1_hash(const char *str);
965inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
966
968constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL;
970constexpr uint32_t FNV1_PRIME = 16777619UL;
971
973template<std::integral T> constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) {
974 using UnsignedT = std::make_unsigned_t<T>;
975 UnsignedT uvalue = static_cast<UnsignedT>(value);
976 for (size_t i = 0; i < sizeof(T); i++) {
977 hash *= FNV1_PRIME;
978 hash ^= (uvalue >> (i * 8)) & 0xFF;
979 }
980 return hash;
981}
983constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) {
984 if (str) {
985 while (*str) {
986 hash *= FNV1_PRIME;
987 hash ^= *str++;
988 }
989 }
990 return hash;
991}
992inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); }
993
995constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) {
996 if (str) {
997 while (*str) {
998 hash ^= *str++;
999 hash *= FNV1_PRIME;
1000 }
1001 }
1002 return hash;
1003}
1004inline uint32_t fnv1a_hash_extend(uint32_t hash, const std::string &str) {
1005 return fnv1a_hash_extend(hash, str.c_str());
1006}
1008template<std::integral T> constexpr uint32_t fnv1a_hash_extend(uint32_t hash, T value) {
1009 using UnsignedT = std::make_unsigned_t<T>;
1010 UnsignedT uvalue = static_cast<UnsignedT>(value);
1011 for (size_t i = 0; i < sizeof(T); i++) {
1012 hash ^= (uvalue >> (i * 8)) & 0xFF;
1013 hash *= FNV1_PRIME;
1014 }
1015 return hash;
1016}
1018constexpr uint32_t fnv1a_hash(const char *str) { return fnv1a_hash_extend(FNV1_OFFSET_BASIS, str); }
1019inline uint32_t fnv1a_hash(const std::string &str) { return fnv1a_hash(str.c_str()); }
1020
1021// micros_to_millis<>() lives in its own lightweight header so hal.h can pull it
1022// in for inline millis_64() without forcing every TU that includes hal.h to
1023// also include the rest of helpers.h.
1024
1032float random_float();
1035bool random_bytes(uint8_t *data, size_t len);
1036
1038
1041
1043constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
1044 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
1045}
1047constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
1048 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
1049}
1051constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
1052 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
1053 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
1054}
1055
1057template<unsigned BITS> constexpr int32_t sign_extend(uint32_t value) {
1058 static_assert(BITS > 0 && BITS <= 32, "BITS must be 1 to 32");
1059 return static_cast<int32_t>(value << (32 - BITS)) >> (32 - BITS);
1060}
1061
1064template<typename T, enable_if_t<std::is_integral<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
1065 if constexpr (sizeof(T) == 1) {
1066 return static_cast<T>(bytes[0]);
1067 } else {
1068 std::make_unsigned_t<T> val = 0;
1069 for (size_t i = 0; i < sizeof(T); i++) {
1070 val <<= 8;
1071 val |= bytes[i];
1072 }
1073 return static_cast<T>(val);
1074 }
1075}
1077template<typename T, enable_if_t<std::is_integral<T>::value, int> = 0>
1078constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
1079 return encode_value<T>(bytes.data());
1080}
1083template<typename T, enable_if_t<std::is_integral<T>::value, int> = 0>
1084constexpr T encode_value_le(const uint8_t *bytes) {
1085 // Loops here grow 16-bit callers by up to 48 bytes on ESP8266 through different inlining
1086 if constexpr (sizeof(T) == 1) {
1087 return static_cast<T>(bytes[0]);
1088 } else if constexpr (sizeof(T) == 2) {
1089 return static_cast<T>(encode_uint16(bytes[1], bytes[0]));
1090 } else {
1091 std::make_unsigned_t<T> val = 0;
1092 for (size_t i = sizeof(T); i > 0; i--) {
1093 val <<= 8;
1094 val |= bytes[i - 1];
1095 }
1096 return static_cast<T>(val);
1097 }
1098}
1100template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1101constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
1102 std::array<uint8_t, sizeof(T)> ret{};
1103 for (size_t i = sizeof(T); i > 0; i--) {
1104 ret[i - 1] = val & 0xFF;
1105 val >>= 8;
1106 }
1107 return ret;
1108}
1109
1112constexpr uint8_t *put_be16(uint8_t *dst, uint16_t value) {
1113 dst[0] = static_cast<uint8_t>(value >> 8);
1114 dst[1] = static_cast<uint8_t>(value);
1115 return dst + 2;
1116}
1117constexpr uint8_t *put_be24(uint8_t *dst, uint32_t value) {
1118 dst[0] = static_cast<uint8_t>(value >> 16);
1119 dst[1] = static_cast<uint8_t>(value >> 8);
1120 dst[2] = static_cast<uint8_t>(value);
1121 return dst + 3;
1122}
1123constexpr uint8_t *put_be32(uint8_t *dst, uint32_t value) {
1124 dst[0] = static_cast<uint8_t>(value >> 24);
1125 dst[1] = static_cast<uint8_t>(value >> 16);
1126 dst[2] = static_cast<uint8_t>(value >> 8);
1127 dst[3] = static_cast<uint8_t>(value);
1128 return dst + 4;
1129}
1130constexpr uint8_t *put_le16(uint8_t *dst, uint16_t value) {
1131 dst[0] = static_cast<uint8_t>(value);
1132 dst[1] = static_cast<uint8_t>(value >> 8);
1133 return dst + 2;
1134}
1135constexpr uint8_t *put_le32(uint8_t *dst, uint32_t value) {
1136 dst[0] = static_cast<uint8_t>(value);
1137 dst[1] = static_cast<uint8_t>(value >> 8);
1138 dst[2] = static_cast<uint8_t>(value >> 16);
1139 dst[3] = static_cast<uint8_t>(value >> 24);
1140 return dst + 4;
1141}
1142
1144constexpr uint8_t bcd_to_uint8(uint8_t bcd) { return (bcd >> 4) * 10 + (bcd & 0x0F); }
1146constexpr uint8_t uint8_to_bcd(uint8_t value) { return ((value / 10) << 4) | (value % 10); }
1147
1150template<typename T> ESPHOME_ALWAYS_INLINE constexpr void assign_bits(T &value, std::type_identity_t<T> mask, bool on) {
1151 if (on) {
1152 value |= mask;
1153 } else {
1154 value &= ~mask;
1155 }
1156}
1157
1159inline uint8_t reverse_bits(uint8_t x) {
1160 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
1161 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
1162 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
1163 return x;
1164}
1166inline uint16_t reverse_bits(uint16_t x) {
1167 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
1168}
1171 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
1172 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
1173}
1174
1176template<typename T> constexpr T convert_big_endian(T val) {
1177#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1178 return byteswap(val);
1179#else
1180 return val;
1181#endif
1182}
1183
1185template<typename T> constexpr T convert_little_endian(T val) {
1186#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1187 return val;
1188#else
1189 return byteswap(val);
1190#endif
1191}
1192
1195inline bool constant_time_equals(const uint8_t *a, const uint8_t *b, size_t len) {
1196 volatile uint8_t diff = 0;
1197 for (size_t i = 0; i < len; i++) {
1198 diff = diff | (a[i] ^ b[i]);
1199 }
1200 return diff == 0;
1201}
1202
1204
1207
1209bool str_equals_case_insensitive(const std::string &a, const std::string &b);
1211bool str_equals_case_insensitive(StringRef a, StringRef b);
1213inline bool str_equals_case_insensitive(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
1214inline bool str_equals_case_insensitive(const std::string &a, const char *b) { return strcasecmp(a.c_str(), b) == 0; }
1215inline bool str_equals_case_insensitive(const char *a, const std::string &b) { return strcasecmp(a, b.c_str()) == 0; }
1216
1218bool str_startswith(const std::string &str, const std::string &start);
1220bool str_endswith(const std::string &str, const std::string &end);
1221
1223bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len);
1224inline bool str_endswith_ignore_case(const char *str, const char *suffix) {
1225 return str_endswith_ignore_case(str, strlen(str), suffix, strlen(suffix));
1226}
1227inline bool str_endswith_ignore_case(const std::string &str, const char *suffix) {
1228 return str_endswith_ignore_case(str.c_str(), str.size(), suffix, strlen(suffix));
1229}
1230
1232bool str_contains_ignore_case_fallback(const char *haystack, const char *needle);
1233
1234#ifdef USE_ESP8266
1237bool str_contains_ignore_case_p(const char *haystack, PGM_P needle);
1241#define str_contains_ignore_case(haystack, needle) str_contains_ignore_case_p(haystack, PSTR(needle))
1242#else
1244inline bool str_contains_ignore_case(const char *haystack, const char *needle) {
1245 if (!needle || !haystack) {
1246 return false;
1247 }
1248
1249// strcasestr is a GNU extension: newlib only declares it when _GNU_SOURCE is set.
1250// ESP32/host builds get it from their framework or from g++ on Linux;
1251// LibreTiny, RP2 and Zephyr do not, so they use the hand-rolled fallback.
1252#if defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1253 return str_contains_ignore_case_fallback(haystack, needle);
1254#else // defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1255 return strcasestr(haystack, needle) != nullptr;
1256#endif // defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1257}
1258#endif // USE_ESP8266
1259
1261constexpr char to_snake_case_char(char c) { return (c == ' ') ? '_' : (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
1262
1264constexpr char to_sanitized_char(char c) {
1265 return (c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ? c : '_';
1266}
1267
1277char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str);
1278
1280template<size_t N> inline char *str_sanitize_to(char (&buffer)[N], const char *str) {
1281 return str_sanitize_to(buffer, N, str);
1282}
1283
1289template<typename ReadByte> inline uint32_t fnv1_hash_object_id(size_t len, ReadByte read_byte) {
1291 for (size_t i = 0; i < len; i++) {
1292 hash *= FNV1_PRIME;
1293 // Apply snake_case (space->underscore, uppercase->lowercase) then sanitize
1294 hash ^= static_cast<uint8_t>(to_sanitized_char(to_snake_case_char(read_byte(i))));
1295 }
1296 return hash;
1297}
1298inline uint32_t fnv1_hash_object_id(const char *str, size_t len) {
1299 return fnv1_hash_object_id(len, [str](size_t i) { return str[i]; });
1300}
1301
1302#ifdef USE_ESP8266
1303// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM)
1304// Format strings must be wrapped with PSTR() macro
1311inline size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt, ...) {
1312 if (pos >= size) {
1313 return size;
1314 }
1315 va_list args;
1316 va_start(args, fmt);
1317 int written = vsnprintf_P(buf + pos, size - pos, fmt, args);
1318 va_end(args);
1319 if (written < 0) {
1320 return pos; // encoding error
1321 }
1322 return std::min(pos + static_cast<size_t>(written), size);
1323}
1324#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
1325#else
1333__attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf, size_t size, size_t pos,
1334 const char *fmt, ...) {
1335 if (pos >= size) {
1336 return size;
1337 }
1338 va_list args;
1340 int written = vsnprintf(buf + pos, size - pos, fmt, args);
1341 va_end(args);
1342 if (written < 0) {
1343 return pos; // encoding error
1344 }
1345 return std::min(pos + static_cast<size_t>(written), size);
1346}
1347#endif
1348
1349#ifdef USE_ESP8266
1359inline size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str) {
1360 if (pos >= size) {
1361 return size;
1362 }
1363 size_t remaining = size - pos - 1; // reserve space for null terminator
1364 size_t len = strnlen_P(str, remaining);
1365 memcpy_P(buf + pos, str, len);
1366 pos += len;
1367 buf[pos] = '\0';
1368 return pos;
1369}
1373#define buf_append_str(buf, size, pos, str) buf_append_str_p(buf, size, pos, PSTR(str))
1374#else
1382inline size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str) {
1383 if (pos >= size) {
1384 return size;
1385 }
1386 size_t remaining = size - pos - 1; // reserve space for null terminator
1387 size_t len = 0;
1388 while (len < remaining && str[len] != '\0') {
1389 len++;
1390 }
1391 memcpy(buf + pos, str, len);
1392 pos += len;
1393 buf[pos] = '\0';
1394 return pos;
1395}
1396#endif
1397
1399static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
1400
1410size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
1411 const char *suffix_ptr, size_t suffix_len);
1412
1414static constexpr size_t MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN = 7;
1415
1421size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len);
1422
1424
1427
1429template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1430optional<T> parse_number(const char *str) {
1431 char *end = nullptr;
1432 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
1433 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
1434 return {};
1435 return value;
1436}
1438template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1439optional<T> parse_number(const std::string &str) {
1440 return parse_number<T>(str.c_str());
1441}
1443template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1444optional<T> parse_number(const char *str) {
1445 char *end = nullptr;
1446 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
1447 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
1448 return {};
1449 return value;
1450}
1452template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1453optional<T> parse_number(const std::string &str) {
1454 return parse_number<T>(str.c_str());
1455}
1457optional<float> parse_float(const char *str);
1459template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
1460 return parse_float(str);
1461}
1463template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
1464optional<T> parse_number(const std::string &str) {
1465 return parse_number<T>(str.c_str());
1466}
1467
1479size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
1481inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
1482 return parse_hex(str, strlen(str), data, count) == 2 * count;
1483}
1485inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
1486 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
1487}
1489inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
1490 data.resize(count);
1491 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
1492}
1494inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
1495 data.resize(count);
1496 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
1497}
1503template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1504optional<T> parse_hex(const char *str, size_t len) {
1505 T val = 0;
1506 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
1507 return {};
1508 return convert_big_endian(val);
1509}
1511template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
1512 return parse_hex<T>(str, strlen(str));
1513}
1515template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
1516 return parse_hex<T>(str.c_str(), str.length());
1517}
1518
1521static constexpr uint8_t INVALID_HEX_CHAR = 255;
1522
1523constexpr uint8_t parse_hex_char(char c) {
1524 if (c >= '0' && c <= '9')
1525 return c - '0';
1526 if (c >= 'A' && c <= 'F')
1527 return c - 'A' + 10;
1528 if (c >= 'a' && c <= 'f')
1529 return c - 'a' + 10;
1530 return INVALID_HEX_CHAR;
1531}
1532
1534ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v, char base) { return v >= 10 ? base + (v - 10) : '0' + v; }
1535
1537ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v) { return format_hex_char(v, 'a'); }
1538
1540ESPHOME_ALWAYS_INLINE inline char format_hex_pretty_char(uint8_t v) { return format_hex_char(v, 'A'); }
1541
1543static constexpr size_t JSON_ESCAPE_MAX_EXPANSION = 6;
1544
1556const char *json_escape_into_buffer(std::span<char> buf, StringRef value, bool short_control_escapes = true);
1557
1560inline char *int8_to_str(char *buf, int8_t val) {
1561 int32_t v = val;
1562 if (v < 0) {
1563 *buf++ = '-';
1564 v = -v;
1565 }
1566 if (v >= 100) {
1567 *buf++ = '1'; // int8 max is 128, so hundreds digit is always 1
1568 v -= 100;
1569 // Must write tens digit (even if 0) after hundreds
1570 int32_t tens = v / 10;
1571 *buf++ = '0' + tens;
1572 v -= tens * 10;
1573 } else if (v >= 10) {
1574 int32_t tens = v / 10;
1575 *buf++ = '0' + tens;
1576 v -= tens * 10;
1577 }
1578 *buf++ = '0' + v;
1579 return buf;
1580}
1581
1586inline char *buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len) {
1587 if (remaining < 2) {
1588 if (remaining >= 1) {
1589 *buf = '\0';
1590 }
1591 return buf;
1592 }
1593 *buf++ = separator;
1594 remaining--;
1595 size_t copy_len = std::min(str_len, remaining - 1);
1596 memcpy(buf, str, copy_len);
1597 buf += copy_len;
1598 *buf = '\0';
1599 return buf;
1600}
1601
1603inline uint32_t small_pow10(int8_t n) { return n == 4 ? 10000 : n == 3 ? 1000 : n == 2 ? 100 : n == 1 ? 10 : 1; }
1604
1606static constexpr size_t UINT32_MAX_STR_SIZE = 11;
1607
1610char *uint32_to_str_unchecked(char *buf, uint32_t val);
1611
1614inline size_t uint32_to_str(std::span<char, UINT32_MAX_STR_SIZE> buf, uint32_t val) {
1615 char *end = uint32_to_str_unchecked(buf.data(), val);
1616 *end = '\0';
1617 return static_cast<size_t>(end - buf.data());
1618}
1619
1623inline char *frac_to_str_unchecked(char *buf, uint32_t frac, uint32_t divisor) {
1624 while (divisor > 0) {
1625 *buf++ = '0' + static_cast<char>(frac / divisor);
1626 frac %= divisor;
1627 divisor /= 10;
1628 }
1629 return buf;
1630}
1631
1633char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1634
1637template<size_t N> inline char *format_hex_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1638 static_assert(N >= 3, "Buffer must hold at least one hex byte (3 chars)");
1639 return format_hex_to(buffer, N, data, length);
1640}
1641
1643template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1644inline char *format_hex_to(char (&buffer)[N], T val) {
1645 static_assert(N >= sizeof(T) * 2 + 1, "Buffer too small for type");
1647 return format_hex_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1648}
1649
1651template<size_t N> inline char *format_hex_to(char (&buffer)[N], const std::vector<uint8_t> &data) {
1652 return format_hex_to(buffer, data.data(), data.size());
1653}
1654
1656template<size_t N, size_t M> inline char *format_hex_to(char (&buffer)[N], const std::array<uint8_t, M> &data) {
1657 return format_hex_to(buffer, data.data(), data.size());
1658}
1659
1661constexpr size_t format_hex_size(size_t byte_count) { return byte_count * 2 + 1; }
1662
1664constexpr size_t format_hex_prefixed_size(size_t byte_count) { return byte_count * 2 + 3; }
1665
1667template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1668inline char *format_hex_prefixed_to(char (&buffer)[N], T val) {
1669 static_assert(N >= sizeof(T) * 2 + 3, "Buffer too small for prefixed hex");
1670 buffer[0] = '0';
1671 buffer[1] = 'x';
1673 format_hex_to(buffer + 2, N - 2, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1674 return buffer;
1675}
1676
1678template<size_t N> inline char *format_hex_prefixed_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1679 static_assert(N >= 5, "Buffer must hold at least '0x' + one hex byte + null");
1680 buffer[0] = '0';
1681 buffer[1] = 'x';
1682 format_hex_to(buffer + 2, N - 2, data, length);
1683 return buffer;
1684}
1685
1687constexpr size_t format_hex_pretty_size(size_t byte_count) { return byte_count * 3; }
1688
1700char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator = ':');
1701
1703template<size_t N>
1704inline char *format_hex_pretty_to(char (&buffer)[N], const uint8_t *data, size_t length, char separator = ':') {
1705 static_assert(N >= 3, "Buffer must hold at least one hex byte");
1706 return format_hex_pretty_to(buffer, N, data, length, separator);
1707}
1708
1710template<size_t N>
1711inline char *format_hex_pretty_to(char (&buffer)[N], const std::vector<uint8_t> &data, char separator = ':') {
1712 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1713}
1714
1716template<size_t N, size_t M>
1717inline char *format_hex_pretty_to(char (&buffer)[N], const std::array<uint8_t, M> &data, char separator = ':') {
1718 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1719}
1720
1722constexpr size_t format_hex_pretty_uint16_size(size_t count) { return count * 5; }
1723
1737char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator = ':');
1738
1740template<size_t N>
1741inline char *format_hex_pretty_to(char (&buffer)[N], const uint16_t *data, size_t length, char separator = ':') {
1742 static_assert(N >= 5, "Buffer must hold at least one hex uint16_t");
1743 return format_hex_pretty_to(buffer, N, data, length, separator);
1744}
1745
1747static constexpr size_t MAC_ADDRESS_SIZE = 6;
1749static constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE = format_hex_pretty_size(MAC_ADDRESS_SIZE);
1751static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1752
1754inline char *format_mac_addr_upper(const uint8_t *mac, char *output) {
1755 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE, ':');
1756}
1757
1759inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
1760 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1761}
1762
1764constexpr size_t format_bin_size(size_t byte_count) { return byte_count * 8 + 1; }
1765
1785char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1786
1788template<size_t N> inline char *format_bin_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1789 static_assert(N >= 9, "Buffer must hold at least one binary byte (9 chars)");
1790 return format_bin_to(buffer, N, data, length);
1791}
1792
1809template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1810inline char *format_bin_to(char (&buffer)[N], T val) {
1811 static_assert(N >= sizeof(T) * 8 + 1, "Buffer too small for type");
1813 return format_bin_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1814}
1815
1824ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
1825
1827static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1828
1830size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals);
1832size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
1833 int8_t accuracy_decimals, StringRef unit_of_measurement);
1834
1836int8_t step_to_accuracy_decimals(float step);
1837
1838size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
1839size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
1840
1845bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
1846
1848
1851
1853void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
1855void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
1856
1858
1861
1863constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
1865constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
1866
1867enum class TemperatureUnit : uint8_t {
1868 CELSIUS = 0,
1869 FAHRENHEIT = 1,
1870 KELVIN = 2,
1871};
1872
1874constexpr float celsius_to(float value, TemperatureUnit unit) {
1875 if (unit == TemperatureUnit::FAHRENHEIT)
1877 if (unit == TemperatureUnit::KELVIN)
1878 return value + 273.15f;
1879 return value;
1880}
1881
1883
1886
1893template<typename... X> struct Callback;
1894
1895template<typename... Ts> struct Callback<void(Ts...)> {
1896 // The inline storage path stores callable bytes in ctx_ via memcpy.
1897 // sizeof equality with uintptr_t ensures void* can round-trip arbitrary bit patterns,
1898 // which combined with flat address spaces on all ESPHome targets means no trap representations.
1899 static_assert(sizeof(void *) == sizeof(std::uintptr_t), "void* must be the same size as uintptr_t");
1900
1901 void (*fn_)(void *, Ts...){nullptr};
1902 void *ctx_{nullptr};
1903
1905 void call(Ts... args) const { this->fn_(this->ctx_, std::forward<Ts>(args)...); }
1906
1909 template<typename F> static constexpr bool fits_inline() {
1910 using DecayF = std::decay_t<F>;
1911 return sizeof(DecayF) <= sizeof(void *) && std::is_trivially_copyable_v<DecayF> &&
1912 std::is_invocable_v<const DecayF &, Ts...>;
1913 }
1914
1917 template<typename F> static Callback create(F &&callable) {
1918 using DecayF = std::decay_t<F>;
1919 if constexpr (fits_inline<F>()) {
1920 // Small trivial callable (e.g. [this]() { this->method(); }) - store inline in ctx.
1921 // Safe under C++20 (P0593R6): byte copy into aligned storage implicitly
1922 // creates objects of implicit-lifetime types (trivially copyable qualifies).
1923 Callback cb; // fn and ctx are zero-initialized by default
1924 // Decay callable to a local variable first. When F is a function reference
1925 // (e.g. void(&)(int)), &callable would point at machine code, not a pointer variable.
1926 DecayF decayed = std::forward<F>(callable);
1927 __builtin_memcpy(&cb.ctx_, &decayed, sizeof(DecayF));
1928 cb.fn_ = [](void *c, Ts... args) {
1929 alignas(DecayF) char buf[sizeof(DecayF)];
1930 __builtin_memcpy(buf, &c, sizeof(DecayF));
1931 (*std::launder(reinterpret_cast<DecayF *>(buf)))(args...);
1932 };
1933 return cb;
1934 } else {
1935 // Large or non-trivial callable - heap allocate.
1936 // Intentionally never freed: callbacks in ESPHome are registered during setup()
1937 // and live for device lifetime. Same lifetime as the previous std::function approach.
1938 auto *stored = new DecayF(std::forward<F>(callable));
1939 return {[](void *c, Ts... args) { (*static_cast<DecayF *>(c))(args...); }, static_cast<void *>(stored)};
1940 }
1941 }
1942
1944 struct Box {
1945 void (*free)(Box *box);
1946 };
1947
1949 template<typename F> static Callback create_boxed(F &&callable) {
1950 struct Boxed : Box {
1951 std::decay_t<F> fn;
1952 };
1953 auto *box = new Boxed{{[](Box *b) { delete static_cast<Boxed *>(b); }}, // NOLINT(cppcoreguidelines-owning-memory)
1954 std::forward<F>(callable)};
1955 return {[](void *c, Ts... args) { static_cast<Boxed *>(static_cast<Box *>(c))->fn(args...); },
1956 static_cast<Box *>(box)};
1957 }
1958
1960 void free_boxed() const {
1961 auto *box = static_cast<Box *>(this->ctx_);
1962 box->free(box);
1963 }
1964};
1965
1967void *callback_manager_grow(void *data, uint16_t size, uint16_t &capacity, size_t elem_size);
1968
1969template<typename... X> class CallbackManager;
1970
1982template<typename... Ts> class CallbackManager<void(Ts...)> {
1983 using CbType = Callback<void(Ts...)>;
1984 static_assert(std::is_trivially_copyable_v<CbType>, "Callback must be trivially copyable");
1985
1986 public:
1987 CallbackManager() = default;
1988 ~CallbackManager() { ::operator delete(this->data_); }
1989
1990 // Non-copyable (would alias data_), movable (for std::map support)
1994 : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
1995 other.data_ = nullptr;
1996 other.size_ = 0;
1997 other.capacity_ = 0;
1998 }
2000 std::swap(this->data_, other.data_);
2001 std::swap(this->size_, other.size_);
2002 std::swap(this->capacity_, other.capacity_);
2003 return *this;
2004 }
2005
2008 template<typename F> void add(F &&callback) { this->add_(CbType::create(std::forward<F>(callback))); }
2009
2011 inline void ESPHOME_ALWAYS_INLINE call(const Ts &...args) {
2012 if (this->size_ != 0) {
2013 for (auto *it = this->data_, *end = it + this->size_; it != end; ++it) {
2014 it->call(args...);
2015 }
2016 }
2017 }
2018 uint16_t size() const { return this->size_; }
2019
2021 void operator()(const Ts &...args) { this->call(args...); }
2022
2023 protected:
2024 template<typename...> friend class LazyCallbackManager;
2027 void add_(CbType cb) {
2028 if (this->size_ == this->capacity_) {
2029 this->data_ =
2030 static_cast<CbType *>(callback_manager_grow(this->data_, this->size_, this->capacity_, sizeof(CbType)));
2031 }
2032 this->data_[this->size_++] = cb;
2033 }
2034 CbType *data_{nullptr};
2035 uint16_t size_{0};
2036 uint16_t capacity_{0};
2037};
2038
2047template<size_t N, typename... X> class StaticCallbackManager;
2048
2049template<size_t N, typename... Ts> class StaticCallbackManager<N, void(Ts...)> {
2050 public:
2053 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
2054
2056 void call(Ts... args) {
2057 for (auto &cb : this->callbacks_)
2058 cb.call(args...);
2059 }
2060 size_t size() const { return this->callbacks_.size(); }
2061
2063 void operator()(Ts... args) { call(args...); }
2064
2065 protected:
2067 void add_(Callback<void(Ts...)> cb) { this->callbacks_.push_back(cb); }
2069};
2070
2071template<typename... X> class LazyCallbackManager;
2072
2088template<typename... Ts> class LazyCallbackManager<void(Ts...)> {
2089 public:
2093 ~LazyCallbackManager() { delete this->callbacks_; }
2094
2095 // Non-copyable and non-movable (entities are never copied or moved)
2100
2102 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
2103
2105 void call(Ts... args) {
2106 if (this->callbacks_) {
2107 this->callbacks_->call(args...);
2108 }
2109 }
2110
2112 size_t size() const { return this->callbacks_ ? this->callbacks_->size() : 0; }
2113
2115 bool empty() const { return !this->callbacks_ || this->callbacks_->size() == 0; }
2116
2118 void operator()(Ts... args) { this->call(args...); }
2119
2120 protected:
2122 void add_(Callback<void(Ts...)> cb) {
2123 if (!this->callbacks_) {
2124 this->callbacks_ = new CallbackManager<void(Ts...)>();
2125 }
2126 this->callbacks_->add_(cb);
2127 }
2128 CallbackManager<void(Ts...)> *callbacks_{nullptr};
2129};
2130
2132template<typename T> class Deduplicator {
2133 public:
2135 bool next(T value) {
2136 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
2137 return false;
2138 }
2139 this->has_value_ = true;
2140 this->value_unknown_ = false;
2141 this->last_value_ = value;
2142 return true;
2143 }
2146 bool ret = !this->value_unknown_;
2147 this->value_unknown_ = true;
2148 return ret;
2149 }
2151 bool has_value() const { return this->has_value_; }
2152
2153 protected:
2154 bool has_value_{false};
2155 bool value_unknown_{false};
2157};
2158
2160template<typename T> class Parented {
2161 public:
2163 Parented(T *parent) : parent_(parent) {}
2164
2166 T *get_parent() const { return parent_; }
2168 void set_parent(T *parent) { parent_ = parent; }
2169
2170 protected:
2171 T *parent_{nullptr};
2172};
2173
2175
2178
2183class Mutex {
2184 public:
2185 Mutex(const Mutex &) = delete;
2186 Mutex &operator=(const Mutex &) = delete;
2187
2188#if defined(USE_ESP8266) || defined(USE_RP2)
2189 // Single-threaded platforms: inline no-ops so the compiler eliminates all call overhead.
2190 Mutex() = default;
2191 ~Mutex() = default;
2192 void lock() {}
2193 bool try_lock() { return true; }
2194 void unlock() {}
2195#elif defined(USE_ESP32) || defined(USE_LIBRETINY)
2196 // FreeRTOS platforms: inline to avoid out-of-line call overhead.
2197 Mutex() { handle_ = xSemaphoreCreateMutex(); }
2198 ~Mutex() = default;
2199 void lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
2200 bool try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
2201 void unlock() { xSemaphoreGive(this->handle_); }
2202
2203 private:
2204 SemaphoreHandle_t handle_;
2205#else
2206 Mutex();
2207 ~Mutex();
2208 void lock();
2209 bool try_lock();
2210 void unlock();
2211
2212 private:
2213 // d-pointer to store private data on new platforms
2214 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
2215#endif
2216};
2217
2223 public:
2224 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
2225 ~LockGuard() { mutex_.unlock(); }
2226
2227 private:
2228 Mutex &mutex_;
2229};
2230
2252 public:
2253#ifdef USE_ESP8266
2254 // Inline: saves two calls per lock, and the lock sits on bit-banged timing paths
2255 ESPHOME_ALWAYS_INLINE InterruptLock() : state_(xt_rsil(15)) {}
2256 ESPHOME_ALWAYS_INLINE ~InterruptLock() { xt_wsr_ps(this->state_); }
2257#else
2260#endif
2261
2262 protected:
2263#if defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
2265#endif
2266};
2267
2277 public:
2278 LwIPLock(const LwIPLock &) = delete;
2279 LwIPLock &operator=(const LwIPLock &) = delete;
2280
2281#if defined(USE_ESP32) || defined(USE_RP2)
2282 // Platforms with potential lwIP core locking — out-of-line implementations in helpers.cpp
2283 LwIPLock();
2284 ~LwIPLock();
2285#ifdef USE_ESP32
2286 private:
2287 // Only the instance that took the core lock releases it; unused without CONFIG_LWIP_TCPIP_CORE_LOCKING
2288 [[maybe_unused]] bool locked_{false};
2289#endif
2290#else
2291 // No lwIP core locking — inline no-ops (empty bodies instead of = default
2292 // to prevent clang-tidy unused-variable warnings at call sites)
2293 LwIPLock() {}
2294 ~LwIPLock() {}
2295#endif
2296};
2297
2298#if defined(USE_ESP8266) && F_CPU != 160000000L
2299// Forward decl from <user_interface.h>
2300// NOLINTNEXTLINE(readability-redundant-declaration)
2301extern "C" bool system_update_cpu_freq(uint8_t freq);
2302#endif
2303
2311 public:
2314#if defined(USE_ESP8266) && F_CPU != 160000000L
2317#else
2318 // Not = default, so clang-tidy does not flag unused variables at call sites
2321#endif
2322};
2323
2330 public:
2332 void start();
2334 void stop();
2335
2337 static bool is_high_frequency() { return num_requests > 0; }
2338
2339 protected:
2340 bool started_{false};
2341 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
2342};
2343
2345void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
2346
2350void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf);
2351
2355const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf);
2356
2357#ifdef USE_ESP32
2359void set_mac_address(uint8_t *mac);
2360
2364bool get_custom_mac_address(uint8_t *mac);
2365#endif
2366
2370
2373bool mac_address_is_valid(const uint8_t *mac);
2374
2377
2379
2382
2383template<typename T> struct RAMDeleter;
2385template<typename T> using RAMUniquePtr = std::unique_ptr<T, RAMDeleter<T>>;
2386
2396template<class T> class RAMAllocator {
2397 public:
2398 using value_type = T;
2399
2400 enum Flags {
2401 NONE = 0, // Perform external allocation and fall back to internal memory
2402 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
2403 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
2404 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
2405 PREFER_INTERNAL = 1 << 3, // Perform internal allocation and fall back to external memory
2406 };
2407
2408 constexpr RAMAllocator() = default;
2409 constexpr RAMAllocator(uint8_t flags) {
2410 if (flags & PREFER_INTERNAL) {
2412 return;
2413 }
2414 const uint8_t alloc_bits = flags & (ALLOC_INTERNAL | ALLOC_EXTERNAL);
2415 if (alloc_bits != 0) {
2416 this->flags_ = alloc_bits;
2417 return;
2418 }
2419 this->flags_ = ALLOC_INTERNAL | ALLOC_EXTERNAL;
2420 }
2421 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
2422
2423 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
2424
2425 T *allocate(size_t n, size_t manual_size) {
2426 size_t size = n * manual_size;
2427 T *ptr = nullptr;
2428#ifdef USE_ESP32
2429 const auto caps = this->get_caps_();
2430 ptr = static_cast<T *>(heap_caps_malloc_prefer(size, caps.num, caps.primary, caps.fallback));
2431#else
2432 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2433 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2434#endif
2435 return ptr;
2436 }
2437
2438 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
2439
2440 T *reallocate(T *p, size_t n, size_t manual_size) {
2441 size_t size = n * manual_size;
2442 T *ptr = nullptr;
2443#ifdef USE_ESP32
2444 const auto caps = this->get_caps_();
2445 ptr = static_cast<T *>(heap_caps_realloc_prefer(p, size, caps.num, caps.primary, caps.fallback));
2446#else
2447 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2448 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2449#endif
2450 return ptr;
2451 }
2452
2453 void deallocate(T *p, size_t n) {
2454 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2455 }
2456
2459 template<typename... Args> RAMUniquePtr<T> make_unique(Args &&...args) {
2460 static_assert(alignof(T) <= alignof(std::max_align_t), "malloc storage cannot hold an over aligned type");
2461 T *p = this->allocate(1);
2462 if (p == nullptr)
2463 return {};
2464 // ::new so a class scoped operator new cannot hide the global placement form
2465 return RAMUniquePtr<T>(::new (p) T(std::forward<Args>(args)...));
2466 }
2467
2470 static_assert(std::is_trivially_default_constructible_v<T>, "elements are left unconstructed");
2471 static_assert(alignof(T) <= alignof(std::max_align_t), "malloc storage cannot hold an over aligned type");
2472 if (n == 0 || n > SIZE_MAX / sizeof(T))
2473 return {};
2474 return RAMUniquePtr<T[]>(this->allocate(n));
2475 }
2476
2480 size_t get_free_heap_size() const {
2481#ifdef USE_ESP8266
2482 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
2483#elif defined(USE_ESP32)
2484 auto max_internal =
2485 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2486 auto max_external =
2487 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2488 return max_internal + max_external;
2489#elif defined(USE_RP2)
2490 return ::rp2040.getFreeHeap();
2491#elif defined(USE_LIBRETINY)
2492 return lt_heap_get_free();
2493#else
2494 return 100000;
2495#endif
2496 }
2497
2502#ifdef USE_ESP8266
2503 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
2504#elif defined(USE_ESP32)
2505 auto max_internal =
2506 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2507 auto max_external =
2508 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2509 return std::max(max_internal, max_external);
2510#else
2511 return this->get_free_heap_size();
2512#endif
2513 }
2514
2515 private:
2516#ifdef USE_ESP32
2517 struct Caps {
2518 uint32_t primary;
2519 uint32_t fallback;
2520 uint8_t num; // distinct capability sets to hand to heap_caps_*_prefer
2521 constexpr Caps(uint32_t primary_caps, uint32_t fallback_caps)
2522 : primary(primary_caps), fallback(fallback_caps), num(primary_caps == fallback_caps ? 1 : 2) {}
2523 };
2524
2531 constexpr Caps get_caps_() const {
2532 constexpr uint32_t external_caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
2533 constexpr uint32_t internal_caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
2534 if (this->flags_ & PREFER_INTERNAL) {
2535 return {internal_caps, external_caps};
2536 }
2537 const uint32_t primary = (this->flags_ & ALLOC_EXTERNAL) ? external_caps : internal_caps;
2538 const uint32_t fallback = (this->flags_ & ALLOC_INTERNAL) ? internal_caps : external_caps;
2539 return {primary, fallback};
2540 }
2541#endif
2542
2543 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
2544};
2545
2546template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
2547
2549template<typename T> struct RAMDeleter {
2550 void operator()(T *p) const {
2551 p->~T();
2553 }
2554};
2556template<typename T> struct RAMDeleter<T[]> {
2557 static_assert(std::is_trivially_destructible_v<T>, "RAMUniquePtr<T[]> is for trivially destructible elements");
2558 void operator()(T *p) const { RAMAllocator<T>().deallocate(p, 1); }
2559};
2560
2565template<typename T, typename U>
2566concept comparable_with = requires(T a, U b) {
2567 { a > b } -> std::convertible_to<bool>;
2568 { a < b } -> std::convertible_to<bool>;
2569};
2570
2571template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
2572 if (value < min)
2573 return min;
2574 return value;
2575}
2576template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
2577 if (value > max)
2578 return max;
2579 return value;
2580}
2581
2584
2589template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
2594template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
2595
2597
2598} // namespace esphome
uint8_t m
Definition bl0906.h:1
void ESPHOME_ALWAYS_INLINE call(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:2011
CallbackManager & operator=(const CallbackManager &)=delete
void operator()(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:2021
CallbackManager & operator=(CallbackManager &&other) noexcept
Definition helpers.h:1999
void add(F &&callback)
Add any callable.
Definition helpers.h:2008
CallbackManager(CallbackManager &&other) noexcept
Definition helpers.h:1993
void add_(CbType cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:2027
CallbackManager(const CallbackManager &)=delete
void append_copy(const T *extra, size_t count)
Appends count elements into one new heap array this owns; the current list and extra may be codegen t...
Definition helpers.h:183
const T & operator[](size_t index) const
Definition helpers.h:172
void merge_copy_(const T *first, size_t first_count, const T *second, size_t second_count)
Definition helpers.h:196
const T & at(size_t index) const
Definition helpers.h:173
constexpr ConstVector()=default
void prepend_copy(const T *extra, size_t count)
Like append_copy(), with extra placed in front of the current list.
Definition helpers.h:185
const T * begin() const
Definition helpers.h:167
void assign_static(const T *data, size_t size)
Codegen only: call before any runtime copy; it does not free a previous owned copy (generated setup()...
Definition helpers.h:177
constexpr ConstVector(const T *data, size_t size)
Definition helpers.h:162
static void copy_items(const T *src, size_t count, T *dst)
Definition helpers.h:205
ConstVector(const ConstVector &)=delete
ConstVector & operator=(const ConstVector &)=delete
void assign_copy(const T *data, size_t size)
Copies the list into a heap array this owns, freeing a previous owned copy.
Definition helpers.h:187
Lightweight read-only view over a const array stored in RODATA (will typically be in flash memory).
Definition helpers.h:131
constexpr bool empty() const
Definition helpers.h:142
const T * begin() const
Definition helpers.h:138
constexpr ConstVector(const T *data, size_t size)
Definition helpers.h:136
const T & at(size_t i) const
Definition helpers.h:144
const constexpr T & operator[](size_t i) const
Definition helpers.h:143
const T * data() const
Definition helpers.h:140
constexpr size_t size() const
Definition helpers.h:141
constexpr ConstVector()=default
const T * end() const
Definition helpers.h:139
Runs the CPU at 160 MHz while alive.
Definition helpers.h:2310
CpuFrequencyBoost & operator=(const CpuFrequencyBoost &)=delete
CpuFrequencyBoost(const CpuFrequencyBoost &)=delete
Helper class to deduplicate items in a series of values.
Definition helpers.h:2132
bool next(T value)
Feeds the next item in the series to the deduplicator and returns false if this is a duplicate.
Definition helpers.h:2135
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:2151
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:2145
bool operator!=(const ConstIterator &other) const
Definition helpers.h:516
ConstIterator(const FixedRingBuffer *buf, index_type pos)
Definition helpers.h:510
bool operator!=(const Iterator &other) const
Definition helpers.h:501
Iterator(FixedRingBuffer *buf, index_type pos)
Definition helpers.h:495
Fixed-capacity circular buffer - allocates once at runtime, never reallocates.
Definition helpers.h:487
FixedRingBuffer & operator=(const FixedRingBuffer &)=delete
ConstIterator begin() const
Definition helpers.h:623
index_type free_space() const
Definition helpers.h:611
bool push(const T &value)
Push a value. Returns false if full.
Definition helpers.h:549
const T & front() const
Definition helpers.h:607
index_type capacity() const
Definition helpers.h:610
void push_overwrite(const T &value)
Push a value, overwriting the oldest if full.
Definition helpers.h:559
void init(index_type capacity)
Allocate capacity - can only be called once.
Definition helpers.h:537
const T & operator[](index_type pos) const
The element pos places after the oldest one; the sum is widened so a small index type cannot truncate...
Definition helpers.h:627
void pop()
Remove the oldest element.
Definition helpers.h:585
void clear()
Clear all elements (reset to empty, keep capacity)
Definition helpers.h:615
index_type wrap_(size_t index) const
Fold an index below 2 * capacity back into the buffer.
Definition helpers.h:631
size_t pop(T *out, size_t len)
Move up to len of the oldest values into out. Returns how many were copied.
Definition helpers.h:593
size_t push(const T *data, size_t len)
Push up to len values without overwriting. Returns how many fit.
Definition helpers.h:571
FixedRingBuffer(const FixedRingBuffer &)=delete
index_type size() const
Definition helpers.h:608
ConstIterator end() const
Definition helpers.h:624
Fixed-capacity vector - sized once through init() or try_init(); push_back never reallocates This avo...
Definition helpers.h:669
const T & at(size_t i) const
Definition helpers.h:858
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:725
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:716
const T * begin() const
Definition helpers.h:863
bool full() const
Definition helpers.h:848
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:748
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:828
const T & operator[](size_t i) const
Definition helpers.h:853
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:852
size_t capacity() const
Definition helpers.h:847
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:833
bool empty() const
Definition helpers.h:846
FixedVector & operator=(const FixedVector &)=delete
FixedVector(const FixedVector &)=delete
void push_back(T &&value)
Add element by move without bounds checking Caller must ensure sufficient capacity was allocated via ...
Definition helpers.h:807
void pop_back()
Remove the last element in place (no reallocation, keeps capacity) Caller must ensure vector is not e...
Definition helpers.h:838
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:819
size_t size() const
Definition helpers.h:845
const T & front() const
Definition helpers.h:829
const T & back() const
Definition helpers.h:834
const T * end() const
Definition helpers.h:864
bool try_init(size_t n)
Definition helpers.h:765
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:732
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:857
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:796
void init(size_t n)
Definition helpers.h:759
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:2329
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.h:2337
void stop()
Stop running the loop continuously.
Definition helpers.cpp:841
void start()
Start running the loop continuously.
Definition helpers.cpp:835
Helper class to disable interrupts.
Definition helpers.h:2251
ESPHOME_ALWAYS_INLINE InterruptLock()
Definition helpers.h:2255
ESPHOME_ALWAYS_INLINE ~InterruptLock()
Definition helpers.h:2256
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
Definition helpers.h:2112
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:2122
void add(F &&callback)
Add any callable. Allocates the underlying CallbackManager on first use.
Definition helpers.h:2102
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:2118
LazyCallbackManager & operator=(LazyCallbackManager &&)=delete
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
Definition helpers.h:2093
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
Definition helpers.h:2105
bool empty() const
Check if any callbacks are registered.
Definition helpers.h:2115
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:2222
LockGuard(Mutex &mutex)
Definition helpers.h:2224
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:2276
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:2183
~Mutex()=default
Definition helpers.cpp:40
void unlock()
Definition helpers.h:2194
Mutex()=default
Definition helpers.cpp:39
bool try_lock()
Definition helpers.h:2193
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
Definition helpers.h:2160
T * get_parent() const
Get the parent of this object.
Definition helpers.h:2166
Parented(T *parent)
Definition helpers.h:2163
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:2168
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
constexpr RAMAllocator(uint8_t flags)
Definition helpers.h:2409
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:2440
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:2480
T * reallocate(T *p, size_t n)
Definition helpers.h:2438
void deallocate(T *p, size_t n)
Definition helpers.h:2453
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
Definition helpers.h:2459
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:2501
T * allocate(size_t n)
Definition helpers.h:2423
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:2421
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
Definition helpers.h:2469
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:2425
constexpr RAMAllocator()=default
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:872
SmallBufferWithHeapFallback(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback & operator=(SmallBufferWithHeapFallback &&)=delete
SmallBufferWithHeapFallback & operator=(const SmallBufferWithHeapFallback &)=delete
SmallBufferWithHeapFallback(SmallBufferWithHeapFallback &&)=delete
Small buffer optimization - stores data inline when small, heap-allocates for large data This avoids ...
Definition helpers.h:224
SmallInlineBuffer(const SmallInlineBuffer &)=delete
uint8_t * init(size_t size)
Resize to size bytes of (uninitialized) storage and return a writable pointer to fill.
Definition helpers.h:272
bool is_inline_() const
Definition helpers.h:294
void set(const uint8_t *src, size_t size)
Set buffer contents, allocating heap if needed.
Definition helpers.h:287
SmallInlineBuffer & operator=(const SmallInlineBuffer &)=delete
size_t size() const
Definition helpers.h:291
uint8_t inline_[InlineSize]
Definition helpers.h:298
SmallInlineBuffer & operator=(SmallInlineBuffer &&other) noexcept
Definition helpers.h:244
const uint8_t * data() const
Definition helpers.h:290
SmallInlineBuffer(SmallInlineBuffer &&other) noexcept
Definition helpers.h:233
void add(F &&callback)
Add any callable.
Definition helpers.h:2053
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:2056
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:2067
StaticVector< Callback< void(Ts...)>, N > callbacks_
Definition helpers.h:2068
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:2063
CallbackManager backed by StaticVector for compile-time-known callback counts.
Definition helpers.h:2047
ConstIterator(const StaticRingBuffer *buf, index_type pos)
Definition helpers.h:429
bool operator!=(const ConstIterator &other) const
Definition helpers.h:435
bool operator!=(const Iterator &other) const
Definition helpers.h:420
Iterator(StaticRingBuffer *buf, index_type pos)
Definition helpers.h:414
Fixed-size circular buffer with FIFO semantics and iteration support.
Definition helpers.h:408
bool push(const T &value)
Definition helpers.h:442
ConstIterator begin() const
Definition helpers.h:473
ConstIterator end() const
Definition helpers.h:474
index_type size() const
Definition helpers.h:461
const T & front() const
Definition helpers.h:460
void clear()
Clear all elements (reset to empty)
Definition helpers.h:465
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:304
const_reverse_iterator rend() const
Definition helpers.h:394
size_t size() const
Definition helpers.h:373
constexpr StaticVector() noexcept
Definition helpers.h:319
reverse_iterator rbegin()
Definition helpers.h:391
const T & operator[](size_t i) const
Definition helpers.h:382
reverse_iterator rend()
Definition helpers.h:392
void push_back(const T &value)
Definition helpers.h:343
bool empty() const
Definition helpers.h:375
static constexpr size_t capacity()
Definition helpers.h:374
void assign(InputIt first, InputIt last)
Definition helpers.h:356
const_reverse_iterator rbegin() const
Definition helpers.h:393
T & operator[](size_t i)
Definition helpers.h:381
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:310
typename std::array< T, N >::iterator iterator
Definition helpers.h:307
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:308
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:309
const T * data() const
Definition helpers.h:379
const_iterator end() const
Definition helpers.h:388
StaticVector(InputIt first, InputIt last)
Definition helpers.h:322
StaticVector(const StaticVector< T, M > &other)
Definition helpers.h:338
StaticVector(std::initializer_list< T > init)
Definition helpers.h:329
void resize(size_t n)
Definition helpers.h:353
const_iterator begin() const
Definition helpers.h:387
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
Functions to constrain the range of arithmetic values.
Definition helpers.h:2566
uint8_t second
uint16_t flags
uint16_t id
std::vector< uint8_t > & out
Definition gif.cpp:49
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
int ret
const char * format
mopeka_std_values val[3]
size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str)
Safely append a PROGMEM string to buffer, returning new position (capped at size).
Definition helpers.h:1359
T clamp_at_most(T value, U max)
Definition helpers.h:2576
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
Definition helpers.cpp:20
constexpr uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init=0)
XOR the bytes of data with size len, starting from init.
Definition helpers.h:949
size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str)
Safely append a string to buffer, returning new position (capped at size).
Definition helpers.h:1382
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:995
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:206
ESPHOME_ALWAYS_INLINE char format_hex_char(uint8_t v, char base)
Convert a nibble (0-15) to hex char with specified base ('a' for lowercase, 'A' for uppercase)
Definition helpers.h:1534
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:95
size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Format name + separator + suffix directly into buffer without heap allocation.
Definition helpers.cpp:277
constexpr T convert_big_endian(T val)
Convert a value between host byte order and big endian (most significant byte first) order.
Definition helpers.h:1176
size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len)
Copy a name into a buffer, cutting it when it does not fit.
Definition helpers.cpp:297
bool str_contains_ignore_case(const char *haystack, const char *needle)
Case-insensitive check if needle string is contained in haystack (no heap allocation).
Definition helpers.h:1244
bool system_update_cpu_freq(uint8_t freq)
std::unique_ptr< T, RAMDeleter< T > > RAMUniquePtr
unique_ptr over RAMAllocator storage
Definition helpers.h:2385
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:1264
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:865
constexpr uint8_t uint8_to_bcd(uint8_t value)
Encode a value from 0 to 99 as a two-digit packed BCD byte, e.g. 59 to 0x59.
Definition helpers.h:1146
ESPHOME_ALWAYS_INLINE char format_hex_pretty_char(uint8_t v)
Convert a nibble (0-15) to uppercase hex char (used for pretty printing)
Definition helpers.h:1540
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1759
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:968
constexpr float celsius_to(float value, TemperatureUnit unit)
Convert degrees Celsius into the given unit.
Definition helpers.h:1874
void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value)
Convert red, green and blue (all 0-1) values to hue (0-360), saturation (0-1) and value (0-1).
Definition helpers.cpp:770
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:35
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:625
size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt,...)
Safely append formatted string to buffer, returning new position (capped at size).
Definition helpers.h:1311
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
Definition helpers.cpp:554
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...
Definition helpers.h:939
uint32_t value
Definition hal.cpp:41
constexpr T convert_little_endian(T val)
Convert a value between host byte order and little endian (least significant byte first) order.
Definition helpers.h:1185
constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value)
Extend a FNV-1 hash with an integer (hashes each byte).
Definition helpers.h:973
ESPHOME_ALWAYS_INLINE constexpr void assign_bits(T &value, std::type_identity_t< T > mask, bool on)
Set the bits of mask in value when on is true, clear them otherwise.
Definition helpers.h:1150
bool base64_decode_int32_vector(const std::string &base64, std::vector< int32_t > &out)
Decode base64/base64url string directly into vector of little-endian int32 values.
Definition helpers.cpp:732
va_end(args)
const void size_t len
Definition hal.h:68
constexpr size_t format_hex_prefixed_size(size_t byte_count)
Calculate buffer size needed for format_hex_prefixed_to: "0xXXXXXXXX...\0" = bytes * 2 + 3.
Definition helpers.h:1664
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:1047
uint32_t small_pow10(int8_t n)
Return 10^n for small non-negative n (0-4) as uint32_t, avoiding float.
Definition helpers.h:1603
std::vector< uint8_t > base64_decode(const std::string &encoded_string)
Decode a base64 string to a byte vector.
char * format_hex_prefixed_to(char(&buffer)[N], T val)
Format an unsigned integer as "0x" prefixed lowercase hex to buffer.
Definition helpers.h:1668
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:103
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:370
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
size_t uint32_to_str(std::span< char, UINT32_MAX_STR_SIZE > buf, uint32_t val)
Write unsigned 32-bit integer to buffer with compile-time size check.
Definition helpers.h:1614
uint16_t size
Definition helpers.cpp:34
bool str_contains_ignore_case_fallback(const char *haystack, const char *needle)
Fallback implementation for case insensitive substring comparison.
Definition helpers.cpp:232
uint32_t fnv1_hash_object_id(size_t len, ReadByte read_byte)
Calculate FNV-1 hash of a string while applying snake_case + sanitize transformations.
Definition helpers.h:1289
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:569
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:169
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1084
T clamp_at_least(T value, U min)
Definition helpers.h:2571
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1430
char * frac_to_str_unchecked(char *buf, uint32_t frac, uint32_t divisor)
Write fractional digits with leading zeros to buffer (internal, no size check).
Definition helpers.h:1623
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:101
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:655
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:10
size_t size_t pos
Definition helpers.h:1333
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:854
char * buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len)
Append a separator char and a string to a buffer, respecting remaining space.
Definition helpers.h:1586
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:889
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
Definition helpers.h:1661
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:210
bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len)
Case-insensitive check if string ends with suffix (no heap allocation).
Definition helpers.cpp:226
constexpr uint8_t bcd_to_uint8(uint8_t bcd)
Decode a two-digit packed BCD byte (tens in the high nibble) to its value, e.g. 0x59 to 59.
Definition helpers.h:1144
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
Definition helpers.cpp:265
void init_array_from(std::array< T, N > &dest, std::initializer_list< T > src)
Initialize a std::array from an initializer_list.
Definition helpers.h:644
char * int8_to_str(char *buf, int8_t val)
Write int8 value to buffer without modulo operations.
Definition helpers.h:1560
size_t value_accuracy_with_uom_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Format value with accuracy and UOM to buffer, returns chars written (excluding null)
Definition helpers.cpp:644
const char * json_escape_into_buffer(std::span< char > buf, StringRef value, bool short_control_escapes)
Copy value into buf, escaping the characters that cannot appear raw inside a JSON string literal.
Definition helpers.cpp:432
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:414
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1687
TemperatureUnit
Definition helpers.h:1867
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:970
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
Definition helpers.h:1064
void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue)
Convert hue (0-360), saturation (0-1) and value (0-1) to red, green and blue (all 0-1).
Definition helpers.cpp:793
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:848
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:135
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1051
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
Definition helpers.h:1112
constexpr uint8_t * put_be24(uint8_t *dst, uint32_t value)
Definition helpers.h:1117
const void * src
Definition hal.h:68
uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first)
Calculate a CRC-8 checksum of data with size len.
Definition helpers.cpp:68
constexpr int32_t sign_extend(uint32_t value)
Sign-extend the low BITS bits of value, e.g. sign_extend<24>(0xFFFFFE) == -2. Higher bits are ignored...
Definition helpers.h:1057
constexpr uint8_t * put_le32(uint8_t *dst, uint32_t value)
Definition helpers.h:1135
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition helpers.h:1863
size_t size_t const char va_start(args, fmt)
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:71
size_t size_t const char * fmt
Definition helpers.h:1334
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1523
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:217
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:1101
bool constant_time_equals(const uint8_t *a, const uint8_t *b, size_t len)
Compare len bytes of a and b in a time that does not depend on where they first differ.
Definition helpers.h:1195
constexpr size_t format_bin_size(size_t byte_count)
Calculate buffer size needed for format_bin_to: "01234567...\0" = bytes * 8 + 1.
Definition helpers.h:1764
int written
Definition helpers.h:1340
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:85
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:1261
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:1865
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:1159
optional< float > parse_float(const char *str)
Parse a decimal floating-point number; plain decimals skip the libc parser.
Definition helpers.cpp:326
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:428
float lerp(float completion, float start, float end)=delete
constexpr uint16_t sum16_bytes(const uint8_t *data, size_t len, uint16_t sum=0)
Add up the bytes of data with size len, truncated to 16 bits.
Definition helpers.h:944
constexpr size_t format_hex_pretty_uint16_size(size_t count)
Calculate buffer size needed for format_hex_pretty_to with uint16_t data: "XXXX:XXXX:....
Definition helpers.h:1722
T remap(U value, U min, U max, T min_out, T max_out)
Remap value from the range (min, max) to (min_out, max_out).
Definition helpers.h:932
bool get_custom_mac_address(uint8_t *mac)
Read the custom MAC address from eFuse into the provided byte array (6 bytes).
Definition helpers.cpp:59
void * callback_manager_grow(void *data, uint16_t size, uint16_t &capacity, size_t elem_size)
Grow a CallbackManager's backing array to exactly size+1. Defined in helpers.cpp.
constexpr uint8_t * put_be32(uint8_t *dst, uint32_t value)
Definition helpers.h:1123
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:218
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:1018
bool str_contains_ignore_case_p(const char *haystack, PGM_P needle)
ESP8266 internal implementation reading the needle from flash — prefer the str_contains_ignore_case m...
Definition helpers.cpp:248
uint16_t uint16_t & capacity
Definition helpers.cpp:34
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1817
@ PARSE_ON
Definition helpers.h:1819
@ PARSE_TOGGLE
Definition helpers.h:1821
@ PARSE_OFF
Definition helpers.h:1820
@ PARSE_NONE
Definition helpers.h:1818
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:919
char * format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as binary string to buffer.
Definition helpers.cpp:533
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1754
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)
Definition helpers.h:1130
static void uint32_t
Heap home of a callable stored by create_boxed(); the header knows how to free it.
Definition helpers.h:1944
static Callback create(F &&callable)
Create from any callable.
Definition helpers.h:1917
void free_boxed() const
Free the callable of a Callback made by create_boxed(); the Callback must not be called afterwards.
Definition helpers.h:1960
static constexpr bool fits_inline()
Whether create() stores F inline in the ctx pointer.
Definition helpers.h:1909
static Callback create_boxed(F &&callable)
Store any callable on the heap with a deleter, for an owner that can later free_boxed() it.
Definition helpers.h:1949
void call(Ts... args) const
Invoke the callback. Only valid on Callbacks created via create(), never on default-constructed insta...
Definition helpers.h:1905
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
Definition helpers.h:1893
void operator()(T *p) const
Definition helpers.h:2558
Destroys and frees RAMAllocator storage. Not convertible: free() needs the address malloc returned.
Definition helpers.h:2549
void operator()(T *p) const
Definition helpers.h:2550
uint8_t end[39]
Definition sun_gtil2.cpp:17
void byteswap()
uint16_t length
Definition tt21100.cpp:0
uint16_t x
Definition tt21100.cpp:5