ESPHome 2026.9.0
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 <span>
19#include <string>
20#include <type_traits>
21#include <utility>
22#include <vector>
23#include <concepts>
24#include <strings.h>
25
28
29// Backward compatibility re-export of heap-allocating helpers.
30// These functions have moved to alloc_helpers.h. External components should
31// update their includes to use #include "esphome/core/alloc_helpers.h" directly.
32// This re-export will be removed in 2026.11.0.
34
35#ifdef USE_ESP8266
36#include <Esp.h>
37#include <pgmspace.h>
38#endif
39
40#ifdef USE_RP2
41#include <Arduino.h>
42#endif
43
44#ifdef USE_ESP32
45#include <esp_system.h>
46#include <esp_heap_caps.h>
47#endif
48
49#if defined(USE_ESP32)
50#include <freertos/FreeRTOS.h>
51#include <freertos/semphr.h>
52#elif defined(USE_LIBRETINY)
53#include <FreeRTOS.h>
54#include <semphr.h>
55#endif
56
57#ifdef USE_HOST
58#include <mutex>
59#endif
60
61#define HOT __attribute__((hot))
62#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
63#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
64#define PACKED __attribute__((packed))
65
66namespace esphome {
67
68// Forward declaration to avoid circular dependency with string_ref.h
69class StringRef;
70
73
74// Keep "using" even after the removal of our backports, to avoid breaking existing code.
75using std::to_string;
76using std::is_trivially_copyable;
77using std::make_unique;
78using std::enable_if_t;
79using std::clamp;
80using std::is_invocable;
81#if __cpp_lib_bit_cast >= 201806
82using std::bit_cast;
83#else
85template<
86 typename To, typename From,
87 enable_if_t<sizeof(To) == sizeof(From) && is_trivially_copyable<From>::value && is_trivially_copyable<To>::value,
88 int> = 0>
89To bit_cast(const From &src) {
90 To dst;
91 memcpy(&dst, &src, sizeof(To));
92 return dst;
93}
94#endif
95
96// clang-format off
97inline float lerp(float completion, float start, float end) = delete; // Please use std::lerp. Notice that it has different order on arguments!
98// clang-format on
99
100// std::byteswap from C++23
101template<typename T> constexpr T byteswap(T n) {
102 T m;
103 for (size_t i = 0; i < sizeof(T); i++)
104 reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
105 return m;
106}
107template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
108#ifdef USE_LIBRETINY
109// LibreTiny's Beken framework redefines __builtin_bswap functions as non-constexpr
110template<> inline uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
111template<> inline uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
112template<> inline uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
113template<> inline int8_t byteswap(int8_t n) { return n; }
114template<> inline int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
115template<> inline int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
116template<> inline int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
117#else
118template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
119template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
120template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
121template<> constexpr int8_t byteswap(int8_t n) { return n; }
122template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
123template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
124template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
125#endif
126
128
131
135
136template<typename T> class ConstVector {
137 public:
138 constexpr ConstVector(const T *data, size_t size) : data_(data), size_(size) {}
139
140 const constexpr T &operator[](size_t i) const { return data_[i]; }
141 constexpr size_t size() const { return size_; }
142 constexpr bool empty() const { return size_ == 0; }
143
144 protected:
145 const T *data_;
146 size_t size_;
147};
148
152template<size_t InlineSize = 8> class SmallInlineBuffer {
153 public:
154 SmallInlineBuffer() = default;
156 if (!this->is_inline_())
157 delete[] this->heap_;
158 }
159
160 // Move constructor
161 SmallInlineBuffer(SmallInlineBuffer &&other) noexcept : len_(other.len_) {
162 if (other.is_inline_()) {
163 memcpy(this->inline_, other.inline_, this->len_);
164 } else {
165 this->heap_ = other.heap_;
166 other.heap_ = nullptr;
167 }
168 other.len_ = 0;
169 }
170
171 // Move assignment
173 if (this != &other) {
174 if (!this->is_inline_())
175 delete[] this->heap_;
176 this->len_ = other.len_;
177 if (other.is_inline_()) {
178 memcpy(this->inline_, other.inline_, this->len_);
179 } else {
180 this->heap_ = other.heap_;
181 other.heap_ = nullptr;
182 }
183 other.len_ = 0;
184 }
185 return *this;
186 }
187
188 // Disable copy (would need deep copy of heap data)
191
192 bool empty() const { return this->len_ == 0; }
193
194 // Conversion to std::span for compatibility with span-based APIs
195 operator std::span<const uint8_t>() const { return std::span<const uint8_t>(this->data(), this->len_); }
196
200 uint8_t *init(size_t size) {
201 // Free existing heap allocation if switching from heap to inline or different heap size
203 delete[] this->heap_;
204 this->heap_ = nullptr; // Defensive: prevent use-after-free if logic changes
205 }
206 // Allocate new heap buffer if needed
207 if (size > InlineSize && (this->is_inline_() || size != this->len_)) {
208 this->heap_ = new uint8_t[size]; // NOLINT(cppcoreguidelines-owning-memory)
209 }
210 this->len_ = size;
211 return this->data();
212 }
213
215 void set(const uint8_t *src, size_t size) { memcpy(this->init(size), src, size); }
216
217 uint8_t *data() { return this->is_inline_() ? this->inline_ : this->heap_; }
218 const uint8_t *data() const { return this->is_inline_() ? this->inline_ : this->heap_; }
219 size_t size() const { return this->len_; }
220
221 protected:
222 bool is_inline_() const { return this->len_ <= InlineSize; }
223
224 size_t len_{0};
225 union {
226 uint8_t inline_[InlineSize]{}; // Zero-init ensures clean initial state
227 uint8_t *heap_;
228 };
229};
230
232template<typename T, size_t N> class StaticVector {
233 public:
234 using value_type = T;
235 using iterator = typename std::array<T, N>::iterator;
236 using const_iterator = typename std::array<T, N>::const_iterator;
237 using reverse_iterator = std::reverse_iterator<iterator>;
238 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
239
240 private:
241 std::array<T, N> data_; // intentionally not value-initialized to avoid memset
242 size_t count_{0};
243
244 public:
245 // Default constructor
246 StaticVector() = default;
247
248 // Iterator range constructor
249 template<typename InputIt> StaticVector(InputIt first, InputIt last) {
250 while (first != last && count_ < N) {
251 data_[count_++] = *first++;
252 }
253 }
254
255 // Initializer list constructor
256 StaticVector(std::initializer_list<T> init) {
257 for (const auto &val : init) {
258 if (count_ >= N)
259 break;
260 data_[count_++] = val;
261 }
262 }
263
264 // Converting constructor from a smaller StaticVector of the same element type
265 template<size_t M> StaticVector(const StaticVector<T, M> &other) : StaticVector(other.begin(), other.end()) {
266 static_assert(M <= N, "Source StaticVector cannot be larger than the destination");
267 }
268
269 // Minimal vector-compatible interface - only what we actually use
270 void push_back(const T &value) {
271 if (count_ < N) {
272 data_[count_++] = value;
273 }
274 }
275
276 // Clear all elements
277 void clear() { count_ = 0; }
278
279 // Assign from iterator range
280 template<typename InputIt> void assign(InputIt first, InputIt last) {
281 count_ = 0;
282 while (first != last && count_ < N) {
283 data_[count_++] = *first++;
284 }
285 }
286
287 // Return reference to next element and increment count (with bounds checking)
289 if (count_ >= N) {
290 // Should never happen with proper size calculation
291 // Return reference to last element to avoid crash
292 return data_[N - 1];
293 }
294 return data_[count_++];
295 }
296
297 size_t size() const { return count_; }
298 static constexpr size_t capacity() { return N; }
299 bool empty() const { return count_ == 0; }
300
301 // Direct access to underlying data
302 T *data() { return data_.data(); }
303 const T *data() const { return data_.data(); }
304
305 T &operator[](size_t i) { return data_[i]; }
306 const T &operator[](size_t i) const { return data_[i]; }
307
308 // For range-based for loops
309 iterator begin() { return data_.begin(); }
310 iterator end() { return data_.begin() + count_; }
311 const_iterator begin() const { return data_.begin(); }
312 const_iterator end() const { return data_.begin() + count_; }
313
314 // Reverse iterators
319
320 // Conversion to std::span for compatibility with span-based APIs
321 operator std::span<T>() { return std::span<T>(data_.data(), count_); }
322 operator std::span<const T>() const { return std::span<const T>(data_.data(), count_); }
323};
324
332template<typename T, size_t N> class StaticRingBuffer {
333 using index_type = std::conditional_t<(N <= std::numeric_limits<uint8_t>::max()), uint8_t, uint16_t>;
334
335 public:
336 class Iterator {
337 public:
338 Iterator(StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
339 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % N]; }
341 ++pos_;
342 return *this;
343 }
344 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
345
346 private:
347 StaticRingBuffer *buf_;
348 index_type pos_;
349 };
350
352 public:
353 ConstIterator(const StaticRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
354 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % N]; }
356 ++pos_;
357 return *this;
358 }
359 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
360
361 private:
362 const StaticRingBuffer *buf_;
363 index_type pos_;
364 };
365
366 bool push(const T &value) {
367 if (this->count_ >= N) {
368 return false;
369 }
370 this->data_[this->tail_] = value;
371 this->tail_ = (this->tail_ + 1) % N;
372 ++this->count_;
373 return true;
374 }
375
376 void pop() {
377 if (this->count_ > 0) {
378 this->head_ = (this->head_ + 1) % N;
379 --this->count_;
380 }
381 }
382
383 T &front() { return this->data_[this->head_]; }
384 const T &front() const { return this->data_[this->head_]; }
385 index_type size() const { return this->count_; }
386 bool empty() const { return this->count_ == 0; }
387
389 void clear() {
390 this->head_ = 0;
391 this->tail_ = 0;
392 this->count_ = 0;
393 }
394
395 Iterator begin() { return Iterator(this, 0); }
396 Iterator end() { return Iterator(this, this->count_); }
397 ConstIterator begin() const { return ConstIterator(this, 0); }
398 ConstIterator end() const { return ConstIterator(this, this->count_); }
399
400 protected:
401 T data_[N];
402 index_type head_{0};
403 index_type tail_{0};
404 index_type count_{0};
405};
406
411template<typename T, size_t MAX_CAPACITY = std::numeric_limits<uint16_t>::max()> class FixedRingBuffer {
412 using index_type = std::conditional_t<
413 (MAX_CAPACITY <= std::numeric_limits<uint8_t>::max()), uint8_t,
414 std::conditional_t<(MAX_CAPACITY <= std::numeric_limits<uint16_t>::max()), uint16_t, uint32_t>>;
415
416 public:
417 class Iterator {
418 public:
419 Iterator(FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
420 T &operator*() { return buf_->data_[(buf_->head_ + pos_) % buf_->capacity_]; }
422 ++pos_;
423 return *this;
424 }
425 bool operator!=(const Iterator &other) const { return pos_ != other.pos_; }
426
427 private:
428 FixedRingBuffer *buf_;
429 index_type pos_;
430 };
431
433 public:
434 ConstIterator(const FixedRingBuffer *buf, index_type pos) : buf_(buf), pos_(pos) {}
435 const T &operator*() const { return buf_->data_[(buf_->head_ + pos_) % buf_->capacity_]; }
437 ++pos_;
438 return *this;
439 }
440 bool operator!=(const ConstIterator &other) const { return pos_ != other.pos_; }
441
442 private:
443 const FixedRingBuffer *buf_;
444 index_type pos_;
445 };
446
447 FixedRingBuffer() = default;
449 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
450 ::operator delete(this->data_);
451 } else {
452 delete[] this->data_;
453 }
454 }
455
456 // Disable copy
459
461 void init(index_type capacity) {
462 if constexpr (std::is_trivially_copyable<T>::value && std::is_trivially_default_constructible<T>::value) {
463 // Raw allocation without initialization (elements are written before read)
464 // NOLINTNEXTLINE(bugprone-sizeof-expression)
465 this->data_ = static_cast<T *>(::operator new(capacity * sizeof(T)));
466 } else {
467 this->data_ = new T[capacity];
468 }
469 this->capacity_ = capacity;
470 }
471
473 bool push(const T &value) {
474 if (this->count_ >= this->capacity_)
475 return false;
476 this->data_[this->tail_] = value;
477 this->tail_ = (this->tail_ + 1) % this->capacity_;
478 ++this->count_;
479 return true;
480 }
481
483 void push_overwrite(const T &value) {
484 this->data_[this->tail_] = value;
485 this->tail_ = (this->tail_ + 1) % this->capacity_;
486 if (this->count_ >= this->capacity_) {
487 // Buffer full - advance head to drop oldest, count stays at capacity
488 this->head_ = this->tail_;
489 } else {
490 ++this->count_;
491 }
492 }
493
495 void pop() {
496 if (this->count_ > 0) {
497 this->head_ = (this->head_ + 1) % this->capacity_;
498 --this->count_;
499 }
500 }
501
502 T &front() { return this->data_[this->head_]; }
503 const T &front() const { return this->data_[this->head_]; }
504 index_type size() const { return this->count_; }
505 bool empty() const { return this->count_ == 0; }
506 index_type capacity() const { return this->capacity_; }
507 bool full() const { return this->count_ == this->capacity_; }
508
510 void clear() {
511 this->head_ = 0;
512 this->tail_ = 0;
513 this->count_ = 0;
514 }
515
516 Iterator begin() { return Iterator(this, 0); }
517 Iterator end() { return Iterator(this, this->count_); }
518 ConstIterator begin() const { return ConstIterator(this, 0); }
519 ConstIterator end() const { return ConstIterator(this, this->count_); }
520
521 protected:
522 T *data_{nullptr};
523 index_type head_{0};
524 index_type tail_{0};
525 index_type count_{0};
526 index_type capacity_{0};
527};
528
533template<typename T, size_t N> inline void init_array_from(std::array<T, N> &dest, std::initializer_list<T> src) {
534#ifdef ESPHOME_DEBUG
535 assert(src.size() == N);
536#endif
537 if constexpr (std::is_trivially_copyable_v<T>) {
538 __builtin_memcpy(dest.data(), src.begin(), N * sizeof(T));
539 } else {
540 size_t i = 0;
541 for (const auto &v : src) {
542 dest[i++] = v;
543 }
544 }
545}
546
547// Abort with a reason that reaches the panic output on ESP32. Elsewhere the literal is dropped
548// before it can land in rodata, which is RAM on ESP8266
549#ifdef USE_ESP32
550#define ESPHOME_ABORT_WITH_REASON(reason) esp_system_abort(reason)
551#else
552#define ESPHOME_ABORT_WITH_REASON(reason) abort()
553#endif
554
558template<typename T> class FixedVector {
559 private:
560 T *data_{nullptr};
561 size_t size_{0};
562 size_t capacity_{0};
563
564 // Helper to destroy all elements without freeing memory
565 void destroy_elements_() {
566 // Only call destructors for non-trivially destructible types
567 if constexpr (!std::is_trivially_destructible<T>::value) {
568 for (size_t i = 0; i < size_; i++) {
569 data_[i].~T();
570 }
571 }
572 }
573
574 // Helper to destroy elements and free memory
575 void cleanup_() {
576 if (data_ != nullptr) {
577 destroy_elements_();
578 free(data_); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
579 }
580 }
581
582 // Helper to reset pointers after cleanup
583 void reset_() {
584 data_ = nullptr;
585 capacity_ = 0;
586 size_ = 0;
587 }
588
589 // Helper to assign from initializer list (shared by constructor and assignment operator)
590 void assign_from_initializer_list_(std::initializer_list<T> init_list) {
591 init(init_list.size());
592 size_t idx = 0;
593 for (const auto &item : init_list) {
594 new (data_ + idx) T(item);
595 ++idx;
596 }
597 size_ = init_list.size();
598 }
599
600 public:
601 FixedVector() = default;
602
605 FixedVector(std::initializer_list<T> init_list) { assign_from_initializer_list_(init_list); }
606
607 ~FixedVector() { cleanup_(); }
608
609 // Disable copy operations (avoid accidental expensive copies)
610 FixedVector(const FixedVector &) = delete;
612
613 // Enable move semantics (allows use in move-only containers like std::vector)
614 FixedVector(FixedVector &&other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
615 other.reset_();
616 }
617
618 // Allow conversion to std::vector
619 operator std::vector<T>() const { return {data_, data_ + size_}; }
620
621 FixedVector &operator=(FixedVector &&other) noexcept {
622 if (this != &other) {
623 // Delete our current data
624 cleanup_();
625 // Take ownership of other's data
626 data_ = other.data_;
627 size_ = other.size_;
628 capacity_ = other.capacity_;
629 // Leave other in valid empty state
630 other.reset_();
631 }
632 return *this;
633 }
634
637 FixedVector &operator=(std::initializer_list<T> init_list) {
638 cleanup_();
639 reset_();
640 assign_from_initializer_list_(init_list);
641 return *this;
642 }
643
644 // Allocate capacity - can be called multiple times to reinit
645 // IMPORTANT: After calling init(), you MUST use push_back() to add elements.
646 // Direct assignment via operator[] does NOT update the size counter.
647 // Aborts on exhaustion; use try_init() to handle failure.
648 void init(size_t n) {
649 if (!try_init(n))
650 ESPHOME_ABORT_WITH_REASON("FixedVector: out of memory");
651 }
652
653 // Same as init(), but returns false when memory is exhausted; the previous storage is freed either way
654 bool try_init(size_t n) {
655 cleanup_();
656 reset_();
657 if (n == 0)
658 return true;
659 if (n > SIZE_MAX / sizeof(T))
660 return false; // the byte count would wrap into a small block
661 // sizeof(T) is correct here for any type T (value types, pointers, etc.)
662 // NOLINTNEXTLINE(bugprone-sizeof-expression,cppcoreguidelines-no-malloc,cppcoreguidelines-owning-memory)
663 data_ = static_cast<T *>(malloc(n * sizeof(T)));
664 if (data_ == nullptr)
665 return false;
666 capacity_ = n;
667 return true;
668 }
669
670 // Clear the vector (destroy all elements, reset size to 0, keep capacity)
671 void clear() {
672 destroy_elements_();
673 size_ = 0;
674 }
675
676 // Release all memory (destroys elements and frees memory)
677 void release() {
678 cleanup_();
679 reset_();
680 }
681
685 void push_back(const T &value) {
686 if (size_ < capacity_) {
687 // Use placement new to construct the object in pre-allocated memory
688 new (&data_[size_]) T(value);
689 size_++;
690 }
691 }
692
696 void push_back(T &&value) {
697 if (size_ < capacity_) {
698 // Use placement new to move-construct the object in pre-allocated memory
699 new (&data_[size_]) T(std::move(value));
700 size_++;
701 }
702 }
703
708 template<typename... Args> T &emplace_back(Args &&...args) {
709 // Use placement new to construct the object in pre-allocated memory
710 new (&data_[size_]) T(std::forward<Args>(args)...);
711 size_++;
712 return data_[size_ - 1];
713 }
714
717 T &front() { return data_[0]; }
718 const T &front() const { return data_[0]; }
719
722 T &back() { return data_[size_ - 1]; }
723 const T &back() const { return data_[size_ - 1]; }
724
727 void pop_back() {
728 if constexpr (!std::is_trivially_destructible<T>::value) {
729 data_[size_ - 1].~T();
730 }
731 size_--;
732 }
733
734 size_t size() const { return size_; }
735 bool empty() const { return size_ == 0; }
736 size_t capacity() const { return capacity_; }
737 bool full() const { return size_ == capacity_; }
738
741 T &operator[](size_t i) { return data_[i]; }
742 const T &operator[](size_t i) const { return data_[i]; }
743
746 T &at(size_t i) { return data_[i]; }
747 const T &at(size_t i) const { return data_[i]; }
748
749 // Iterator support for range-based for loops
750 T *begin() { return data_; }
751 T *end() { return data_ + size_; }
752 const T *begin() const { return data_; }
753 const T *end() const { return data_ + size_; }
754};
755
761template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
762 public:
764 static_assert(std::is_trivially_default_constructible_v<T> && std::is_trivially_destructible_v<T>,
765 "the heap fallback leaves elements unconstructed");
766 if (size <= STACK_SIZE) {
767 this->buffer_ = this->stack_buffer_;
768 } else {
769 if (size <= SIZE_MAX / sizeof(T)) {
770 // NOLINTNEXTLINE(bugprone-sizeof-expression,cppcoreguidelines-no-malloc,cppcoreguidelines-owning-memory)
771 this->heap_buffer_ = static_cast<T *>(malloc(size * sizeof(T)));
772 }
773 // Callers write through get() unchecked, so exhaustion aborts like the new[] it replaces
774 if (this->heap_buffer_ == nullptr)
775 ESPHOME_ABORT_WITH_REASON("SmallBufferWithHeapFallback: out of memory");
776 this->buffer_ = this->heap_buffer_;
777 }
778 }
779 ~SmallBufferWithHeapFallback() { free(this->heap_buffer_); } // NOLINT(cppcoreguidelines-no-malloc)
780
781 // Delete copy and move operations to prevent double-delete
786
787 T *get() { return this->buffer_; }
788
789 private:
790 T stack_buffer_[STACK_SIZE];
791 T *heap_buffer_{nullptr};
792 T *buffer_;
793};
794
796
799
803int8_t ilog10(float value);
804
808inline float pow10_int(int8_t exp) {
809 float result = 1.0f;
810 if (exp >= 0) {
811 for (int8_t i = 0; i < exp; i++)
812 result *= 10.0f;
813 } else {
814 for (int8_t i = exp; i < 0; i++)
815 result /= 10.0f;
816 }
817 return result;
818}
819
821template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
822 return (value - min) * (max_out - min_out) / (max - min) + min_out;
823}
824
826uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc = 0x00, uint8_t poly = 0x8C, bool msb_first = false);
827
829uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc = 0xffff, uint16_t reverse_poly = 0xa001,
830 bool refin = false, bool refout = false);
831uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc = 0, uint16_t poly = 0x1021, bool refin = false,
832 bool refout = false);
833
836uint32_t fnv1_hash(const char *str);
837inline uint32_t fnv1_hash(const std::string &str) { return fnv1_hash(str.c_str()); }
838
840constexpr uint32_t FNV1_OFFSET_BASIS = 2166136261UL;
842constexpr uint32_t FNV1_PRIME = 16777619UL;
843
845template<std::integral T> constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value) {
846 using UnsignedT = std::make_unsigned_t<T>;
847 UnsignedT uvalue = static_cast<UnsignedT>(value);
848 for (size_t i = 0; i < sizeof(T); i++) {
849 hash *= FNV1_PRIME;
850 hash ^= (uvalue >> (i * 8)) & 0xFF;
851 }
852 return hash;
853}
855constexpr uint32_t fnv1_hash_extend(uint32_t hash, const char *str) {
856 if (str) {
857 while (*str) {
858 hash *= FNV1_PRIME;
859 hash ^= *str++;
860 }
861 }
862 return hash;
863}
864inline uint32_t fnv1_hash_extend(uint32_t hash, const std::string &str) { return fnv1_hash_extend(hash, str.c_str()); }
865
867constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str) {
868 if (str) {
869 while (*str) {
870 hash ^= *str++;
871 hash *= FNV1_PRIME;
872 }
873 }
874 return hash;
875}
876inline uint32_t fnv1a_hash_extend(uint32_t hash, const std::string &str) {
877 return fnv1a_hash_extend(hash, str.c_str());
878}
880template<std::integral T> constexpr uint32_t fnv1a_hash_extend(uint32_t hash, T value) {
881 using UnsignedT = std::make_unsigned_t<T>;
882 UnsignedT uvalue = static_cast<UnsignedT>(value);
883 for (size_t i = 0; i < sizeof(T); i++) {
884 hash ^= (uvalue >> (i * 8)) & 0xFF;
885 hash *= FNV1_PRIME;
886 }
887 return hash;
888}
890constexpr uint32_t fnv1a_hash(const char *str) { return fnv1a_hash_extend(FNV1_OFFSET_BASIS, str); }
891inline uint32_t fnv1a_hash(const std::string &str) { return fnv1a_hash(str.c_str()); }
892
893// micros_to_millis<>() lives in its own lightweight header so hal.h can pull it
894// in for inline millis_64() without forcing every TU that includes hal.h to
895// also include the rest of helpers.h.
896
904float random_float();
907bool random_bytes(uint8_t *data, size_t len);
908
910
913
915constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb) {
916 return (static_cast<uint16_t>(msb) << 8) | (static_cast<uint16_t>(lsb));
917}
919constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3) {
920 return (static_cast<uint32_t>(byte1) << 16) | (static_cast<uint32_t>(byte2) << 8) | (static_cast<uint32_t>(byte3));
921}
923constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4) {
924 return (static_cast<uint32_t>(byte1) << 24) | (static_cast<uint32_t>(byte2) << 16) |
925 (static_cast<uint32_t>(byte3) << 8) | (static_cast<uint32_t>(byte4));
926}
927
929template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
930 T val = 0;
931 for (size_t i = 0; i < sizeof(T); i++) {
932 val <<= 8;
933 val |= bytes[i];
934 }
935 return val;
936}
938template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
939constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
940 return encode_value<T>(bytes.data());
941}
943template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
944constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
945 std::array<uint8_t, sizeof(T)> ret{};
946 for (size_t i = sizeof(T); i > 0; i--) {
947 ret[i - 1] = val & 0xFF;
948 val >>= 8;
949 }
950 return ret;
951}
952
954inline uint8_t reverse_bits(uint8_t x) {
955 x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
956 x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
957 x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
958 return x;
959}
961inline uint16_t reverse_bits(uint16_t x) {
962 return (reverse_bits(static_cast<uint8_t>(x & 0xFF)) << 8) | reverse_bits(static_cast<uint8_t>((x >> 8) & 0xFF));
963}
966 return (reverse_bits(static_cast<uint16_t>(x & 0xFFFF)) << 16) |
967 reverse_bits(static_cast<uint16_t>((x >> 16) & 0xFFFF));
968}
969
971template<typename T> constexpr T convert_big_endian(T val) {
972#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
973 return byteswap(val);
974#else
975 return val;
976#endif
977}
978
980template<typename T> constexpr T convert_little_endian(T val) {
981#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
982 return val;
983#else
984 return byteswap(val);
985#endif
986}
987
989
992
994bool str_equals_case_insensitive(const std::string &a, const std::string &b);
996bool str_equals_case_insensitive(StringRef a, StringRef b);
998inline bool str_equals_case_insensitive(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
999inline bool str_equals_case_insensitive(const std::string &a, const char *b) { return strcasecmp(a.c_str(), b) == 0; }
1000inline bool str_equals_case_insensitive(const char *a, const std::string &b) { return strcasecmp(a, b.c_str()) == 0; }
1001
1003bool str_startswith(const std::string &str, const std::string &start);
1005bool str_endswith(const std::string &str, const std::string &end);
1006
1008bool str_endswith_ignore_case(const char *str, size_t str_len, const char *suffix, size_t suffix_len);
1009inline bool str_endswith_ignore_case(const char *str, const char *suffix) {
1010 return str_endswith_ignore_case(str, strlen(str), suffix, strlen(suffix));
1011}
1012inline bool str_endswith_ignore_case(const std::string &str, const char *suffix) {
1013 return str_endswith_ignore_case(str.c_str(), str.size(), suffix, strlen(suffix));
1014}
1015
1017bool str_contains_ignore_case_fallback(const char *haystack, const char *needle);
1018
1019#ifdef USE_ESP8266
1022bool str_contains_ignore_case_p(const char *haystack, PGM_P needle);
1026#define str_contains_ignore_case(haystack, needle) str_contains_ignore_case_p(haystack, PSTR(needle))
1027#else
1029inline bool str_contains_ignore_case(const char *haystack, const char *needle) {
1030 if (!needle || !haystack) {
1031 return false;
1032 }
1033
1034// strcasestr is a GNU extension: newlib only declares it when _GNU_SOURCE is set.
1035// ESP32/host builds get it from their framework or from g++ on Linux;
1036// LibreTiny, RP2 and Zephyr do not, so they use the hand-rolled fallback.
1037#if defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1038 return str_contains_ignore_case_fallback(haystack, needle);
1039#else // defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1040 return strcasestr(haystack, needle) != nullptr;
1041#endif // defined(USE_LIBRETINY) || defined(USE_RP2) || defined(USE_ZEPHYR)
1042}
1043#endif // USE_ESP8266
1044
1045// str_truncate moved to alloc_helpers.h - remove this include before 2026.11.0
1046
1047// str_until, str_lower_case, str_upper_case moved to alloc_helpers.h - remove this comment before 2026.11.0
1048
1050constexpr char to_snake_case_char(char c) { return (c == ' ') ? '_' : (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
1051// str_snake_case moved to alloc_helpers.h - remove this comment before 2026.11.0
1052
1054constexpr char to_sanitized_char(char c) {
1055 return (c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ? c : '_';
1056}
1057
1067char *str_sanitize_to(char *buffer, size_t buffer_size, const char *str);
1068
1070template<size_t N> inline char *str_sanitize_to(char (&buffer)[N], const char *str) {
1071 return str_sanitize_to(buffer, N, str);
1072}
1073
1074// str_sanitize moved to alloc_helpers.h - remove this comment before 2026.11.0
1075
1080inline uint32_t fnv1_hash_object_id(const char *str, size_t len) {
1082 for (size_t i = 0; i < len; i++) {
1083 hash *= FNV1_PRIME;
1084 // Apply snake_case (space->underscore, uppercase->lowercase) then sanitize
1085 hash ^= static_cast<uint8_t>(to_sanitized_char(to_snake_case_char(str[i])));
1086 }
1087 return hash;
1088}
1089
1090// str_snprintf, str_sprintf moved to alloc_helpers.h - remove this comment before 2026.11.0
1091
1092#ifdef USE_ESP8266
1093// ESP8266: Use vsnprintf_P to keep format strings in flash (PROGMEM)
1094// Format strings must be wrapped with PSTR() macro
1101inline size_t buf_append_printf_p(char *buf, size_t size, size_t pos, PGM_P fmt, ...) {
1102 if (pos >= size) {
1103 return size;
1104 }
1105 va_list args;
1106 va_start(args, fmt);
1107 int written = vsnprintf_P(buf + pos, size - pos, fmt, args);
1108 va_end(args);
1109 if (written < 0) {
1110 return pos; // encoding error
1111 }
1112 return std::min(pos + static_cast<size_t>(written), size);
1113}
1114#define buf_append_printf(buf, size, pos, fmt, ...) buf_append_printf_p(buf, size, pos, PSTR(fmt), ##__VA_ARGS__)
1115#else
1123__attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf, size_t size, size_t pos,
1124 const char *fmt, ...) {
1125 if (pos >= size) {
1126 return size;
1127 }
1128 va_list args;
1130 int written = vsnprintf(buf + pos, size - pos, fmt, args);
1131 va_end(args);
1132 if (written < 0) {
1133 return pos; // encoding error
1134 }
1135 return std::min(pos + static_cast<size_t>(written), size);
1136}
1137#endif
1138
1139#ifdef USE_ESP8266
1149inline size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str) {
1150 if (pos >= size) {
1151 return size;
1152 }
1153 size_t remaining = size - pos - 1; // reserve space for null terminator
1154 size_t len = strnlen_P(str, remaining);
1155 memcpy_P(buf + pos, str, len);
1156 pos += len;
1157 buf[pos] = '\0';
1158 return pos;
1159}
1163#define buf_append_str(buf, size, pos, str) buf_append_str_p(buf, size, pos, PSTR(str))
1164#else
1172inline size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str) {
1173 if (pos >= size) {
1174 return size;
1175 }
1176 size_t remaining = size - pos - 1; // reserve space for null terminator
1177 size_t len = 0;
1178 while (len < remaining && str[len] != '\0') {
1179 len++;
1180 }
1181 memcpy(buf + pos, str, len);
1182 pos += len;
1183 buf[pos] = '\0';
1184 return pos;
1185}
1186#endif
1187
1189static constexpr size_t MAX_NAME_WITH_SUFFIX_SIZE = 128;
1190
1200size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep,
1201 const char *suffix_ptr, size_t suffix_len);
1202
1204
1207
1209template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1210optional<T> parse_number(const char *str) {
1211 char *end = nullptr;
1212 unsigned long value = ::strtoul(str, &end, 10); // NOLINT(google-runtime-int)
1213 if (end == str || *end != '\0' || value > std::numeric_limits<T>::max())
1214 return {};
1215 return value;
1216}
1218template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_unsigned<T>::value), int> = 0>
1219optional<T> parse_number(const std::string &str) {
1220 return parse_number<T>(str.c_str());
1221}
1223template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1224optional<T> parse_number(const char *str) {
1225 char *end = nullptr;
1226 signed long value = ::strtol(str, &end, 10); // NOLINT(google-runtime-int)
1227 if (end == str || *end != '\0' || value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max())
1228 return {};
1229 return value;
1230}
1232template<typename T, enable_if_t<(std::is_integral<T>::value && std::is_signed<T>::value), int> = 0>
1233optional<T> parse_number(const std::string &str) {
1234 return parse_number<T>(str.c_str());
1235}
1237template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0> optional<T> parse_number(const char *str) {
1238 char *end = nullptr;
1239 float value = ::strtof(str, &end);
1240 if (end == str || *end != '\0' || value == HUGE_VALF)
1241 return {};
1242 return value;
1243}
1245template<typename T, enable_if_t<(std::is_same<T, float>::value), int> = 0>
1246optional<T> parse_number(const std::string &str) {
1247 return parse_number<T>(str.c_str());
1248}
1249
1261size_t parse_hex(const char *str, size_t len, uint8_t *data, size_t count);
1263inline bool parse_hex(const char *str, uint8_t *data, size_t count) {
1264 return parse_hex(str, strlen(str), data, count) == 2 * count;
1265}
1267inline bool parse_hex(const std::string &str, uint8_t *data, size_t count) {
1268 return parse_hex(str.c_str(), str.length(), data, count) == 2 * count;
1269}
1271inline bool parse_hex(const char *str, std::vector<uint8_t> &data, size_t count) {
1272 data.resize(count);
1273 return parse_hex(str, strlen(str), data.data(), count) == 2 * count;
1274}
1276inline bool parse_hex(const std::string &str, std::vector<uint8_t> &data, size_t count) {
1277 data.resize(count);
1278 return parse_hex(str.c_str(), str.length(), data.data(), count) == 2 * count;
1279}
1285template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1286optional<T> parse_hex(const char *str, size_t len) {
1287 T val = 0;
1288 if (len > 2 * sizeof(T) || parse_hex(str, len, reinterpret_cast<uint8_t *>(&val), sizeof(T)) == 0)
1289 return {};
1290 return convert_big_endian(val);
1291}
1293template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const char *str) {
1294 return parse_hex<T>(str, strlen(str));
1295}
1297template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> optional<T> parse_hex(const std::string &str) {
1298 return parse_hex<T>(str.c_str(), str.length());
1299}
1300
1303static constexpr uint8_t INVALID_HEX_CHAR = 255;
1304
1305constexpr uint8_t parse_hex_char(char c) {
1306 if (c >= '0' && c <= '9')
1307 return c - '0';
1308 if (c >= 'A' && c <= 'F')
1309 return c - 'A' + 10;
1310 if (c >= 'a' && c <= 'f')
1311 return c - 'a' + 10;
1312 return INVALID_HEX_CHAR;
1313}
1314
1316ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v, char base) { return v >= 10 ? base + (v - 10) : '0' + v; }
1317
1319ESPHOME_ALWAYS_INLINE inline char format_hex_char(uint8_t v) { return format_hex_char(v, 'a'); }
1320
1322ESPHOME_ALWAYS_INLINE inline char format_hex_pretty_char(uint8_t v) { return format_hex_char(v, 'A'); }
1323
1325static constexpr size_t JSON_ESCAPE_MAX_EXPANSION = 6;
1326
1338const char *json_escape_into_buffer(std::span<char> buf, StringRef value, bool short_control_escapes = true);
1339
1342inline char *int8_to_str(char *buf, int8_t val) {
1343 int32_t v = val;
1344 if (v < 0) {
1345 *buf++ = '-';
1346 v = -v;
1347 }
1348 if (v >= 100) {
1349 *buf++ = '1'; // int8 max is 128, so hundreds digit is always 1
1350 v -= 100;
1351 // Must write tens digit (even if 0) after hundreds
1352 int32_t tens = v / 10;
1353 *buf++ = '0' + tens;
1354 v -= tens * 10;
1355 } else if (v >= 10) {
1356 int32_t tens = v / 10;
1357 *buf++ = '0' + tens;
1358 v -= tens * 10;
1359 }
1360 *buf++ = '0' + v;
1361 return buf;
1362}
1363
1368inline char *buf_append_sep_str(char *buf, size_t remaining, char separator, const char *str, size_t str_len) {
1369 if (remaining < 2) {
1370 if (remaining >= 1) {
1371 *buf = '\0';
1372 }
1373 return buf;
1374 }
1375 *buf++ = separator;
1376 remaining--;
1377 size_t copy_len = std::min(str_len, remaining - 1);
1378 memcpy(buf, str, copy_len);
1379 buf += copy_len;
1380 *buf = '\0';
1381 return buf;
1382}
1383
1385inline uint32_t small_pow10(int8_t n) { return n == 3 ? 1000 : n == 2 ? 100 : n == 1 ? 10 : 1; }
1386
1388static constexpr size_t UINT32_MAX_STR_SIZE = 11;
1389
1392char *uint32_to_str_unchecked(char *buf, uint32_t val);
1393
1396inline size_t uint32_to_str(std::span<char, UINT32_MAX_STR_SIZE> buf, uint32_t val) {
1397 char *end = uint32_to_str_unchecked(buf.data(), val);
1398 *end = '\0';
1399 return static_cast<size_t>(end - buf.data());
1400}
1401
1405inline char *frac_to_str_unchecked(char *buf, uint32_t frac, uint32_t divisor) {
1406 while (divisor > 0) {
1407 *buf++ = '0' + static_cast<char>(frac / divisor);
1408 frac %= divisor;
1409 divisor /= 10;
1410 }
1411 return buf;
1412}
1413
1415char *format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1416
1419template<size_t N> inline char *format_hex_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1420 static_assert(N >= 3, "Buffer must hold at least one hex byte (3 chars)");
1421 return format_hex_to(buffer, N, data, length);
1422}
1423
1425template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1426inline char *format_hex_to(char (&buffer)[N], T val) {
1427 static_assert(N >= sizeof(T) * 2 + 1, "Buffer too small for type");
1429 return format_hex_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1430}
1431
1433template<size_t N> inline char *format_hex_to(char (&buffer)[N], const std::vector<uint8_t> &data) {
1434 return format_hex_to(buffer, data.data(), data.size());
1435}
1436
1438template<size_t N, size_t M> inline char *format_hex_to(char (&buffer)[N], const std::array<uint8_t, M> &data) {
1439 return format_hex_to(buffer, data.data(), data.size());
1440}
1441
1443constexpr size_t format_hex_size(size_t byte_count) { return byte_count * 2 + 1; }
1444
1446constexpr size_t format_hex_prefixed_size(size_t byte_count) { return byte_count * 2 + 3; }
1447
1449template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1450inline char *format_hex_prefixed_to(char (&buffer)[N], T val) {
1451 static_assert(N >= sizeof(T) * 2 + 3, "Buffer too small for prefixed hex");
1452 buffer[0] = '0';
1453 buffer[1] = 'x';
1455 format_hex_to(buffer + 2, N - 2, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1456 return buffer;
1457}
1458
1460template<size_t N> inline char *format_hex_prefixed_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1461 static_assert(N >= 5, "Buffer must hold at least '0x' + one hex byte + null");
1462 buffer[0] = '0';
1463 buffer[1] = 'x';
1464 format_hex_to(buffer + 2, N - 2, data, length);
1465 return buffer;
1466}
1467
1469constexpr size_t format_hex_pretty_size(size_t byte_count) { return byte_count * 3; }
1470
1482char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator = ':');
1483
1485template<size_t N>
1486inline char *format_hex_pretty_to(char (&buffer)[N], const uint8_t *data, size_t length, char separator = ':') {
1487 static_assert(N >= 3, "Buffer must hold at least one hex byte");
1488 return format_hex_pretty_to(buffer, N, data, length, separator);
1489}
1490
1492template<size_t N>
1493inline char *format_hex_pretty_to(char (&buffer)[N], const std::vector<uint8_t> &data, char separator = ':') {
1494 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1495}
1496
1498template<size_t N, size_t M>
1499inline char *format_hex_pretty_to(char (&buffer)[N], const std::array<uint8_t, M> &data, char separator = ':') {
1500 return format_hex_pretty_to(buffer, data.data(), data.size(), separator);
1501}
1502
1504constexpr size_t format_hex_pretty_uint16_size(size_t count) { return count * 5; }
1505
1519char *format_hex_pretty_to(char *buffer, size_t buffer_size, const uint16_t *data, size_t length, char separator = ':');
1520
1522template<size_t N>
1523inline char *format_hex_pretty_to(char (&buffer)[N], const uint16_t *data, size_t length, char separator = ':') {
1524 static_assert(N >= 5, "Buffer must hold at least one hex uint16_t");
1525 return format_hex_pretty_to(buffer, N, data, length, separator);
1526}
1527
1529static constexpr size_t MAC_ADDRESS_SIZE = 6;
1531static constexpr size_t MAC_ADDRESS_PRETTY_BUFFER_SIZE = format_hex_pretty_size(MAC_ADDRESS_SIZE);
1533static constexpr size_t MAC_ADDRESS_BUFFER_SIZE = MAC_ADDRESS_SIZE * 2 + 1;
1534
1536inline char *format_mac_addr_upper(const uint8_t *mac, char *output) {
1537 return format_hex_pretty_to(output, MAC_ADDRESS_PRETTY_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE, ':');
1538}
1539
1541inline void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output) {
1542 format_hex_to(output, MAC_ADDRESS_BUFFER_SIZE, mac, MAC_ADDRESS_SIZE);
1543}
1544
1545// format_mac_address_pretty, format_hex (all overloads) moved to alloc_helpers.h
1546// Remove this comment and the template overloads below before 2026.11.0
1547
1550template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_hex(T val) {
1552 return format_hex(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1553}
1556template<std::size_t N> std::string format_hex(const std::array<uint8_t, N> &data) {
1557 return format_hex(data.data(), data.size());
1558}
1559
1560// format_hex_pretty (all overloads) moved to alloc_helpers.h
1561// Remove this comment and the template overload below before 2026.11.0
1562
1565template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1566std::string format_hex_pretty(T val, char separator = '.', bool show_length = true) {
1568 return format_hex_pretty(reinterpret_cast<uint8_t *>(&val), sizeof(T), separator, show_length);
1569}
1570
1572constexpr size_t format_bin_size(size_t byte_count) { return byte_count * 8 + 1; }
1573
1593char *format_bin_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length);
1594
1596template<size_t N> inline char *format_bin_to(char (&buffer)[N], const uint8_t *data, size_t length) {
1597 static_assert(N >= 9, "Buffer must hold at least one binary byte (9 chars)");
1598 return format_bin_to(buffer, N, data, length);
1599}
1600
1617template<size_t N, typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
1618inline char *format_bin_to(char (&buffer)[N], T val) {
1619 static_assert(N >= sizeof(T) * 8 + 1, "Buffer too small for type");
1621 return format_bin_to(buffer, reinterpret_cast<const uint8_t *>(&val), sizeof(T));
1622}
1623
1624// format_bin moved to alloc_helpers.h - remove this comment and template overload before 2026.11.0
1625
1628template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> std::string format_bin(T val) {
1630 return format_bin(reinterpret_cast<uint8_t *>(&val), sizeof(T));
1631}
1632
1641ParseOnOffState parse_on_off(const char *str, const char *on = nullptr, const char *off = nullptr);
1642
1643// value_accuracy_to_string moved to alloc_helpers.h - remove this comment before 2026.11.0
1644
1646static constexpr size_t VALUE_ACCURACY_MAX_LEN = 64;
1647
1649size_t value_accuracy_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value, int8_t accuracy_decimals);
1651size_t value_accuracy_with_uom_to_buf(std::span<char, VALUE_ACCURACY_MAX_LEN> buf, float value,
1652 int8_t accuracy_decimals, StringRef unit_of_measurement);
1653
1655int8_t step_to_accuracy_decimals(float step);
1656
1657// base64_encode (both overloads), base64_decode (vector overload) moved to alloc_helpers.h
1658// Remove this comment before 2026.11.0
1659size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
1660size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
1661
1666bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
1667
1669
1672
1674void rgb_to_hsv(float red, float green, float blue, int &hue, float &saturation, float &value);
1676void hsv_to_rgb(int hue, float saturation, float value, float &red, float &green, float &blue);
1677
1679
1682
1684constexpr float celsius_to_fahrenheit(float value) { return value * 1.8f + 32.0f; }
1686constexpr float fahrenheit_to_celsius(float value) { return (value - 32.0f) / 1.8f; }
1687
1688enum class TemperatureUnit : uint8_t {
1689 CELSIUS = 0,
1690 FAHRENHEIT = 1,
1691 KELVIN = 2,
1692};
1693
1695
1698
1704template<typename... X> struct Callback;
1705
1706template<typename... Ts> struct Callback<void(Ts...)> {
1707 // The inline storage path stores callable bytes in ctx_ via memcpy.
1708 // sizeof equality with uintptr_t ensures void* can round-trip arbitrary bit patterns,
1709 // which combined with flat address spaces on all ESPHome targets means no trap representations.
1710 static_assert(sizeof(void *) == sizeof(std::uintptr_t), "void* must be the same size as uintptr_t");
1711
1712 void (*fn_)(void *, Ts...){nullptr};
1713 void *ctx_{nullptr};
1714
1716 void call(Ts... args) const { this->fn_(this->ctx_, std::forward<Ts>(args)...); }
1717
1720 template<typename F> static Callback create(F &&callable) {
1721 using DecayF = std::decay_t<F>;
1722 if constexpr (sizeof(DecayF) <= sizeof(void *) && std::is_trivially_copyable_v<DecayF>) {
1723 // Small trivial callable (e.g. [this]() { this->method(); }) - store inline in ctx.
1724 // Safe under C++20 (P0593R6): byte copy into aligned storage implicitly
1725 // creates objects of implicit-lifetime types (trivially copyable qualifies).
1726 Callback cb; // fn and ctx are zero-initialized by default
1727 // Decay callable to a local variable first. When F is a function reference
1728 // (e.g. void(&)(int)), &callable would point at machine code, not a pointer variable.
1729 DecayF decayed = std::forward<F>(callable);
1730 __builtin_memcpy(&cb.ctx_, &decayed, sizeof(DecayF));
1731 cb.fn_ = [](void *c, Ts... args) {
1732 alignas(DecayF) char buf[sizeof(DecayF)];
1733 __builtin_memcpy(buf, &c, sizeof(DecayF));
1734 (*std::launder(reinterpret_cast<DecayF *>(buf)))(args...);
1735 };
1736 return cb;
1737 } else {
1738 // Large or non-trivial callable - heap allocate.
1739 // Intentionally never freed: callbacks in ESPHome are registered during setup()
1740 // and live for device lifetime. Same lifetime as the previous std::function approach.
1741 auto *stored = new DecayF(std::forward<F>(callable));
1742 return {[](void *c, Ts... args) { (*static_cast<DecayF *>(c))(args...); }, static_cast<void *>(stored)};
1743 }
1744 }
1745};
1746
1748void *callback_manager_grow(void *data, uint16_t size, uint16_t &capacity, size_t elem_size);
1749
1750template<typename... X> class CallbackManager;
1751
1763template<typename... Ts> class CallbackManager<void(Ts...)> {
1764 using CbType = Callback<void(Ts...)>;
1765 static_assert(std::is_trivially_copyable_v<CbType>, "Callback must be trivially copyable");
1766
1767 public:
1768 CallbackManager() = default;
1769 ~CallbackManager() { ::operator delete(this->data_); }
1770
1771 // Non-copyable (would alias data_), movable (for std::map support)
1775 : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
1776 other.data_ = nullptr;
1777 other.size_ = 0;
1778 other.capacity_ = 0;
1779 }
1781 std::swap(this->data_, other.data_);
1782 std::swap(this->size_, other.size_);
1783 std::swap(this->capacity_, other.capacity_);
1784 return *this;
1785 }
1786
1789 template<typename F> void add(F &&callback) { this->add_(CbType::create(std::forward<F>(callback))); }
1790
1792 inline void ESPHOME_ALWAYS_INLINE call(const Ts &...args) {
1793 if (this->size_ != 0) {
1794 for (auto *it = this->data_, *end = it + this->size_; it != end; ++it) {
1795 it->call(args...);
1796 }
1797 }
1798 }
1799 uint16_t size() const { return this->size_; }
1800
1802 void operator()(const Ts &...args) { this->call(args...); }
1803
1804 protected:
1805 template<typename...> friend class LazyCallbackManager;
1808 void add_(CbType cb) {
1809 if (this->size_ == this->capacity_) {
1810 this->data_ =
1811 static_cast<CbType *>(callback_manager_grow(this->data_, this->size_, this->capacity_, sizeof(CbType)));
1812 }
1813 this->data_[this->size_++] = cb;
1814 }
1815 CbType *data_{nullptr};
1816 uint16_t size_{0};
1817 uint16_t capacity_{0};
1818};
1819
1828template<size_t N, typename... X> class StaticCallbackManager;
1829
1830template<size_t N, typename... Ts> class StaticCallbackManager<N, void(Ts...)> {
1831 public:
1834 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
1835
1837 void call(Ts... args) {
1838 for (auto &cb : this->callbacks_)
1839 cb.call(args...);
1840 }
1841 size_t size() const { return this->callbacks_.size(); }
1842
1844 void operator()(Ts... args) { call(args...); }
1845
1846 protected:
1848 void add_(Callback<void(Ts...)> cb) { this->callbacks_.push_back(cb); }
1850};
1851
1852template<typename... X> class LazyCallbackManager;
1853
1869template<typename... Ts> class LazyCallbackManager<void(Ts...)> {
1870 public:
1874 ~LazyCallbackManager() { delete this->callbacks_; }
1875
1876 // Non-copyable and non-movable (entities are never copied or moved)
1881
1883 template<typename F> void add(F &&callback) { this->add_(Callback<void(Ts...)>::create(std::forward<F>(callback))); }
1884
1886 void call(Ts... args) {
1887 if (this->callbacks_) {
1888 this->callbacks_->call(args...);
1889 }
1890 }
1891
1893 size_t size() const { return this->callbacks_ ? this->callbacks_->size() : 0; }
1894
1896 bool empty() const { return !this->callbacks_ || this->callbacks_->size() == 0; }
1897
1899 void operator()(Ts... args) { this->call(args...); }
1900
1901 protected:
1903 void add_(Callback<void(Ts...)> cb) {
1904 if (!this->callbacks_) {
1905 this->callbacks_ = new CallbackManager<void(Ts...)>();
1906 }
1907 this->callbacks_->add_(cb);
1908 }
1909 CallbackManager<void(Ts...)> *callbacks_{nullptr};
1910};
1911
1913template<typename T> class Deduplicator {
1914 public:
1916 bool next(T value) {
1917 if (this->has_value_ && !this->value_unknown_ && this->last_value_ == value) {
1918 return false;
1919 }
1920 this->has_value_ = true;
1921 this->value_unknown_ = false;
1922 this->last_value_ = value;
1923 return true;
1924 }
1927 bool ret = !this->value_unknown_;
1928 this->value_unknown_ = true;
1929 return ret;
1930 }
1932 bool has_value() const { return this->has_value_; }
1933
1934 protected:
1935 bool has_value_{false};
1936 bool value_unknown_{false};
1938};
1939
1941template<typename T> class Parented {
1942 public:
1944 Parented(T *parent) : parent_(parent) {}
1945
1947 T *get_parent() const { return parent_; }
1949 void set_parent(T *parent) { parent_ = parent; }
1950
1951 protected:
1952 T *parent_{nullptr};
1953};
1954
1956
1959
1964class Mutex {
1965 public:
1966 Mutex(const Mutex &) = delete;
1967 Mutex &operator=(const Mutex &) = delete;
1968
1969#if defined(USE_ESP8266) || defined(USE_RP2)
1970 // Single-threaded platforms: inline no-ops so the compiler eliminates all call overhead.
1971 Mutex() = default;
1972 ~Mutex() = default;
1973 void lock() {}
1974 bool try_lock() { return true; }
1975 void unlock() {}
1976#elif defined(USE_ESP32) || defined(USE_LIBRETINY)
1977 // FreeRTOS platforms: inline to avoid out-of-line call overhead.
1978 Mutex() { handle_ = xSemaphoreCreateMutex(); }
1979 ~Mutex() = default;
1980 void lock() { xSemaphoreTake(this->handle_, portMAX_DELAY); }
1981 bool try_lock() { return xSemaphoreTake(this->handle_, 0) == pdTRUE; }
1982 void unlock() { xSemaphoreGive(this->handle_); }
1983
1984 private:
1985 SemaphoreHandle_t handle_;
1986#else
1987 Mutex();
1988 ~Mutex();
1989 void lock();
1990 bool try_lock();
1991 void unlock();
1992
1993 private:
1994 // d-pointer to store private data on new platforms
1995 void *handle_; // NOLINT(clang-diagnostic-unused-private-field)
1996#endif
1997};
1998
2004 public:
2005 LockGuard(Mutex &mutex) : mutex_(mutex) { mutex_.lock(); }
2006 ~LockGuard() { mutex_.unlock(); }
2007
2008 private:
2009 Mutex &mutex_;
2010};
2011
2033 public:
2034 InterruptLock();
2036
2037 protected:
2038#if defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
2040#endif
2041};
2042
2052 public:
2053 LwIPLock(const LwIPLock &) = delete;
2054 LwIPLock &operator=(const LwIPLock &) = delete;
2055
2056#if defined(USE_ESP32) || defined(USE_RP2)
2057 // Platforms with potential lwIP core locking — out-of-line implementations in helpers.cpp
2058 LwIPLock();
2059 ~LwIPLock();
2060#else
2061 // No lwIP core locking — inline no-ops (empty bodies instead of = default
2062 // to prevent clang-tidy unused-variable warnings at call sites)
2065#endif
2066};
2067
2074 public:
2076 void start();
2078 void stop();
2079
2081 static bool is_high_frequency() { return num_requests > 0; }
2082
2083 protected:
2084 bool started_{false};
2085 static uint8_t num_requests; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
2086};
2087
2089void get_mac_address_raw(uint8_t *mac); // NOLINT(readability-non-const-parameter)
2090
2091// get_mac_address, get_mac_address_pretty moved to alloc_helpers.h - remove this comment before 2026.11.0
2092
2096void get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_BUFFER_SIZE> buf);
2097
2101const char *get_mac_address_pretty_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf);
2102
2103#ifdef USE_ESP32
2105void set_mac_address(uint8_t *mac);
2106
2110bool get_custom_mac_address(uint8_t *mac);
2111#endif
2112
2116
2119bool mac_address_is_valid(const uint8_t *mac);
2120
2123
2125
2128
2129template<typename T> struct RAMDeleter;
2131template<typename T> using RAMUniquePtr = std::unique_ptr<T, RAMDeleter<T>>;
2132
2142template<class T> class RAMAllocator {
2143 public:
2144 using value_type = T;
2145
2146 enum Flags {
2147 NONE = 0, // Perform external allocation and fall back to internal memory
2148 ALLOC_EXTERNAL = 1 << 0, // Perform external allocation only.
2149 ALLOC_INTERNAL = 1 << 1, // Perform internal allocation only.
2150 ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
2151 PREFER_INTERNAL = 1 << 3, // Perform internal allocation and fall back to external memory
2152 };
2153
2154 constexpr RAMAllocator() = default;
2155 constexpr RAMAllocator(uint8_t flags) {
2156 if (flags & PREFER_INTERNAL) {
2158 return;
2159 }
2160 const uint8_t alloc_bits = flags & (ALLOC_INTERNAL | ALLOC_EXTERNAL);
2161 if (alloc_bits != 0) {
2162 this->flags_ = alloc_bits;
2163 return;
2164 }
2165 this->flags_ = ALLOC_INTERNAL | ALLOC_EXTERNAL;
2166 }
2167 template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
2168
2169 T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }
2170
2171 T *allocate(size_t n, size_t manual_size) {
2172 size_t size = n * manual_size;
2173 T *ptr = nullptr;
2174#ifdef USE_ESP32
2175 const auto caps = this->get_caps_();
2176 ptr = static_cast<T *>(heap_caps_malloc_prefer(size, 2, caps[0], caps[1]));
2177#else
2178 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2179 ptr = static_cast<T *>(malloc(size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2180#endif
2181 return ptr;
2182 }
2183
2184 T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); }
2185
2186 T *reallocate(T *p, size_t n, size_t manual_size) {
2187 size_t size = n * manual_size;
2188 T *ptr = nullptr;
2189#ifdef USE_ESP32
2190 const auto caps = this->get_caps_();
2191 ptr = static_cast<T *>(heap_caps_realloc_prefer(p, size, 2, caps[0], caps[1]));
2192#else
2193 // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported
2194 ptr = static_cast<T *>(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2195#endif
2196 return ptr;
2197 }
2198
2199 void deallocate(T *p, size_t n) {
2200 free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc)
2201 }
2202
2205 template<typename... Args> RAMUniquePtr<T> make_unique(Args &&...args) {
2206 static_assert(alignof(T) <= alignof(std::max_align_t), "malloc storage cannot hold an over aligned type");
2207 T *p = this->allocate(1);
2208 if (p == nullptr)
2209 return {};
2210 // ::new so a class scoped operator new cannot hide the global placement form
2211 return RAMUniquePtr<T>(::new (p) T(std::forward<Args>(args)...));
2212 }
2213
2216 static_assert(std::is_trivially_default_constructible_v<T>, "elements are left unconstructed");
2217 static_assert(alignof(T) <= alignof(std::max_align_t), "malloc storage cannot hold an over aligned type");
2218 if (n == 0 || n > SIZE_MAX / sizeof(T))
2219 return {};
2220 return RAMUniquePtr<T[]>(this->allocate(n));
2221 }
2222
2226 size_t get_free_heap_size() const {
2227#ifdef USE_ESP8266
2228 return ESP.getFreeHeap(); // NOLINT(readability-static-accessed-through-instance)
2229#elif defined(USE_ESP32)
2230 auto max_internal =
2231 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2232 auto max_external =
2233 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2234 return max_internal + max_external;
2235#elif defined(USE_RP2)
2236 return ::rp2040.getFreeHeap();
2237#elif defined(USE_LIBRETINY)
2238 return lt_heap_get_free();
2239#else
2240 return 100000;
2241#endif
2242 }
2243
2248#ifdef USE_ESP8266
2249 return ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
2250#elif defined(USE_ESP32)
2251 auto max_internal =
2252 this->flags_ & ALLOC_INTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL) : 0;
2253 auto max_external =
2254 this->flags_ & ALLOC_EXTERNAL ? heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM) : 0;
2255 return std::max(max_internal, max_external);
2256#else
2257 return this->get_free_heap_size();
2258#endif
2259 }
2260
2261 private:
2262#ifdef USE_ESP32
2268 std::array<uint32_t, 2> get_caps_() const {
2269 constexpr uint32_t external_caps = MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT;
2270 constexpr uint32_t internal_caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
2271 if (this->flags_ & PREFER_INTERNAL) {
2272 return {internal_caps, external_caps};
2273 }
2274 const uint32_t primary = (this->flags_ & ALLOC_EXTERNAL) ? external_caps : internal_caps;
2275 const uint32_t fallback = (this->flags_ & ALLOC_INTERNAL) ? internal_caps : external_caps;
2276 return {primary, fallback};
2277 }
2278#endif
2279
2280 uint8_t flags_{ALLOC_INTERNAL | ALLOC_EXTERNAL};
2281};
2282
2283template<class T> using ExternalRAMAllocator = RAMAllocator<T>;
2284
2286template<typename T> struct RAMDeleter {
2287 void operator()(T *p) const {
2288 p->~T();
2290 }
2291};
2293template<typename T> struct RAMDeleter<T[]> {
2294 static_assert(std::is_trivially_destructible_v<T>, "RAMUniquePtr<T[]> is for trivially destructible elements");
2295 void operator()(T *p) const { RAMAllocator<T>().deallocate(p, 1); }
2296};
2297
2302template<typename T, typename U>
2303concept comparable_with = requires(T a, U b) {
2304 { a > b } -> std::convertible_to<bool>;
2305 { a < b } -> std::convertible_to<bool>;
2306};
2307
2308template<std::totally_ordered T, comparable_with<T> U> T clamp_at_least(T value, U min) {
2309 if (value < min)
2310 return min;
2311 return value;
2312}
2313template<std::totally_ordered T, comparable_with<T> U> T clamp_at_most(T value, U max) {
2314 if (value > max)
2315 return max;
2316 return value;
2317}
2318
2321
2326template<typename T, enable_if_t<!std::is_pointer<T>::value, int> = 0> T id(T value) { return value; }
2331template<typename T, enable_if_t<std::is_pointer<T *>::value, int> = 0> T &id(T *value) { return *value; }
2332
2334
2335} // namespace esphome
Heap-allocating helper functions.
uint8_t m
Definition bl0906.h:1
void ESPHOME_ALWAYS_INLINE call(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:1792
CallbackManager & operator=(const CallbackManager &)=delete
void operator()(const Ts &...args)
Call all callbacks in this manager.
Definition helpers.h:1802
CallbackManager & operator=(CallbackManager &&other) noexcept
Definition helpers.h:1780
void add(F &&callback)
Add any callable.
Definition helpers.h:1789
CallbackManager(CallbackManager &&other) noexcept
Definition helpers.h:1774
void add_(CbType cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1808
CallbackManager(const CallbackManager &)=delete
Lightweight read-only view over a const array stored in RODATA (will typically be in flash memory) Av...
Definition helpers.h:136
const constexpr T & operator[](size_t i) const
Definition helpers.h:140
constexpr bool empty() const
Definition helpers.h:142
constexpr ConstVector(const T *data, size_t size)
Definition helpers.h:138
constexpr size_t size() const
Definition helpers.h:141
Helper class to deduplicate items in a series of values.
Definition helpers.h:1913
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:1916
bool has_value() const
Returns true if this deduplicator has processed any items.
Definition helpers.h:1932
bool next_unknown()
Returns true if the deduplicator's value was previously known.
Definition helpers.h:1926
bool operator!=(const ConstIterator &other) const
Definition helpers.h:440
ConstIterator(const FixedRingBuffer *buf, index_type pos)
Definition helpers.h:434
bool operator!=(const Iterator &other) const
Definition helpers.h:425
Iterator(FixedRingBuffer *buf, index_type pos)
Definition helpers.h:419
Fixed-capacity circular buffer - allocates once at runtime, never reallocates.
Definition helpers.h:411
FixedRingBuffer & operator=(const FixedRingBuffer &)=delete
ConstIterator begin() const
Definition helpers.h:518
bool push(const T &value)
Push a value. Returns false if full.
Definition helpers.h:473
const T & front() const
Definition helpers.h:503
index_type capacity() const
Definition helpers.h:506
void push_overwrite(const T &value)
Push a value, overwriting the oldest if full.
Definition helpers.h:483
void init(index_type capacity)
Allocate capacity - can only be called once.
Definition helpers.h:461
void pop()
Remove the oldest element.
Definition helpers.h:495
void clear()
Clear all elements (reset to empty, keep capacity)
Definition helpers.h:510
FixedRingBuffer(const FixedRingBuffer &)=delete
index_type size() const
Definition helpers.h:504
ConstIterator end() const
Definition helpers.h:519
Fixed-capacity vector - sized once through init() or try_init(); push_back never reallocates This avo...
Definition helpers.h:558
const T & at(size_t i) const
Definition helpers.h:747
FixedVector(FixedVector &&other) noexcept
Definition helpers.h:614
FixedVector(std::initializer_list< T > init_list)
Constructor from initializer list - allocates exact size needed This enables brace initialization: Fi...
Definition helpers.h:605
const T * begin() const
Definition helpers.h:752
bool full() const
Definition helpers.h:737
FixedVector & operator=(std::initializer_list< T > init_list)
Assignment from initializer list - avoids temporary and move overhead This enables: FixedVector<int> ...
Definition helpers.h:637
T & front()
Access first element (no bounds checking - matches std::vector behavior) Caller must ensure vector is...
Definition helpers.h:717
const T & operator[](size_t i) const
Definition helpers.h:742
T & operator[](size_t i)
Access element without bounds checking (matches std::vector behavior) Caller must ensure index is val...
Definition helpers.h:741
size_t capacity() const
Definition helpers.h:736
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:722
bool empty() const
Definition helpers.h:735
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:696
void pop_back()
Remove the last element in place (no reallocation, keeps capacity) Caller must ensure vector is not e...
Definition helpers.h:727
T & emplace_back(Args &&...args)
Emplace element without bounds checking - constructs in-place with arguments Caller must ensure suffi...
Definition helpers.h:708
size_t size() const
Definition helpers.h:734
const T & front() const
Definition helpers.h:718
const T & back() const
Definition helpers.h:723
const T * end() const
Definition helpers.h:753
bool try_init(size_t n)
Definition helpers.h:654
FixedVector & operator=(FixedVector &&other) noexcept
Definition helpers.h:621
T & at(size_t i)
Access element with bounds checking (matches std::vector behavior) Note: No exception thrown on out o...
Definition helpers.h:746
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:685
void init(size_t n)
Definition helpers.h:648
Helper class to request loop() to be called as fast as possible.
Definition helpers.h:2073
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.h:2081
void stop()
Stop running the loop continuously.
Definition helpers.cpp:817
void start()
Start running the loop continuously.
Definition helpers.cpp:811
Helper class to disable interrupts.
Definition helpers.h:2032
LazyCallbackManager & operator=(const LazyCallbackManager &)=delete
LazyCallbackManager(const LazyCallbackManager &)=delete
size_t size() const
Return the number of registered callbacks.
Definition helpers.h:1893
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1903
void add(F &&callback)
Add any callable. Allocates the underlying CallbackManager on first use.
Definition helpers.h:1883
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1899
LazyCallbackManager & operator=(LazyCallbackManager &&)=delete
~LazyCallbackManager()
Destructor - clean up allocated CallbackManager if any.
Definition helpers.h:1874
void call(Ts... args)
Call all callbacks in this manager. No-op if no callbacks registered.
Definition helpers.h:1886
bool empty() const
Check if any callbacks are registered.
Definition helpers.h:1896
LazyCallbackManager(LazyCallbackManager &&)=delete
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:2003
LockGuard(Mutex &mutex)
Definition helpers.h:2005
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:2051
LwIPLock(const LwIPLock &)=delete
LwIPLock & operator=(const LwIPLock &)=delete
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1964
~Mutex()=default
Definition helpers.cpp:36
void unlock()
Definition helpers.h:1975
Mutex()=default
Definition helpers.cpp:35
bool try_lock()
Definition helpers.h:1974
Mutex(const Mutex &)=delete
Mutex & operator=(const Mutex &)=delete
Helper class to easily give an object a parent of type T.
Definition helpers.h:1941
T * get_parent() const
Get the parent of this object.
Definition helpers.h:1947
Parented(T *parent)
Definition helpers.h:1944
void set_parent(T *parent)
Set the parent of this object.
Definition helpers.h:1949
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2142
constexpr RAMAllocator(uint8_t flags)
Definition helpers.h:2155
T * reallocate(T *p, size_t n, size_t manual_size)
Definition helpers.h:2186
size_t get_free_heap_size() const
Return the total heap space available via this allocator.
Definition helpers.h:2226
T * reallocate(T *p, size_t n)
Definition helpers.h:2184
void deallocate(T *p, size_t n)
Definition helpers.h:2199
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
Definition helpers.h:2205
size_t get_max_free_block_size() const
Return the maximum size block this allocator could allocate.
Definition helpers.h:2247
T * allocate(size_t n)
Definition helpers.h:2169
constexpr RAMAllocator(const RAMAllocator< U > &other)
Definition helpers.h:2167
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:2215
T * allocate(size_t n, size_t manual_size)
Definition helpers.h:2171
constexpr RAMAllocator()=default
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:761
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:152
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:200
bool is_inline_() const
Definition helpers.h:222
void set(const uint8_t *src, size_t size)
Set buffer contents, allocating heap if needed.
Definition helpers.h:215
SmallInlineBuffer & operator=(const SmallInlineBuffer &)=delete
size_t size() const
Definition helpers.h:219
uint8_t inline_[InlineSize]
Definition helpers.h:226
SmallInlineBuffer & operator=(SmallInlineBuffer &&other) noexcept
Definition helpers.h:172
const uint8_t * data() const
Definition helpers.h:218
SmallInlineBuffer(SmallInlineBuffer &&other) noexcept
Definition helpers.h:161
void add(F &&callback)
Add any callable.
Definition helpers.h:1834
void call(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1837
void add_(Callback< void(Ts...)> cb)
Non-template core to avoid code duplication per lambda type.
Definition helpers.h:1848
StaticVector< Callback< void(Ts...)>, N > callbacks_
Definition helpers.h:1849
void operator()(Ts... args)
Call all callbacks in this manager.
Definition helpers.h:1844
CallbackManager backed by StaticVector for compile-time-known callback counts.
Definition helpers.h:1828
ConstIterator(const StaticRingBuffer *buf, index_type pos)
Definition helpers.h:353
bool operator!=(const ConstIterator &other) const
Definition helpers.h:359
bool operator!=(const Iterator &other) const
Definition helpers.h:344
Iterator(StaticRingBuffer *buf, index_type pos)
Definition helpers.h:338
Fixed-size circular buffer with FIFO semantics and iteration support.
Definition helpers.h:332
bool push(const T &value)
Definition helpers.h:366
ConstIterator begin() const
Definition helpers.h:397
ConstIterator end() const
Definition helpers.h:398
index_type size() const
Definition helpers.h:385
const T & front() const
Definition helpers.h:384
void clear()
Clear all elements (reset to empty)
Definition helpers.h:389
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:232
const_reverse_iterator rend() const
Definition helpers.h:318
size_t size() const
Definition helpers.h:297
reverse_iterator rbegin()
Definition helpers.h:315
const T & operator[](size_t i) const
Definition helpers.h:306
reverse_iterator rend()
Definition helpers.h:316
void push_back(const T &value)
Definition helpers.h:270
bool empty() const
Definition helpers.h:299
static constexpr size_t capacity()
Definition helpers.h:298
void assign(InputIt first, InputIt last)
Definition helpers.h:280
const_reverse_iterator rbegin() const
Definition helpers.h:317
T & operator[](size_t i)
Definition helpers.h:305
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition helpers.h:238
typename std::array< T, N >::iterator iterator
Definition helpers.h:235
typename std::array< T, N >::const_iterator const_iterator
Definition helpers.h:236
std::reverse_iterator< iterator > reverse_iterator
Definition helpers.h:237
const T * data() const
Definition helpers.h:303
const_iterator end() const
Definition helpers.h:312
StaticVector(InputIt first, InputIt last)
Definition helpers.h:249
StaticVector(const StaticVector< T, M > &other)
Definition helpers.h:265
StaticVector(std::initializer_list< T > init)
Definition helpers.h:256
const_iterator begin() const
Definition helpers.h:311
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
Functions to constrain the range of arithmetic values.
Definition helpers.h:2303
uint16_t flags
uint16_t id
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:1149
T clamp_at_most(T value, U max)
Definition helpers.h:2313
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
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:1172
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:867
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:197
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:1316
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:86
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:271
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:971
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:1029
std::unique_ptr< T, RAMDeleter< T > > RAMUniquePtr
unique_ptr over RAMAllocator storage
Definition helpers.h:2131
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:1054
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:843
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:1322
void format_mac_addr_lower_no_sep(const uint8_t *mac, char *output)
Format MAC address as xxxxxxxxxxxxxx (lowercase, no separators)
Definition helpers.h:1541
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:840
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:746
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:26
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:558
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:1101
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:485
std::string format_bin(const uint8_t *data, size_t length)
Format the byte array data of length len in binary.
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:980
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:845
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:708
va_end(args)
const void size_t len
Definition hal.h:64
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:1446
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:919
uint32_t small_pow10(int8_t n)
Return 10^n for small non-negative n (0-3) as uint32_t, avoiding float.
Definition helpers.h:1385
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:1450
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:119
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:293
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:425
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:1396
uint16_t size
Definition helpers.cpp:25
bool str_contains_ignore_case_fallback(const char *haystack, const char *needle)
Fallback implementation for case insensitive substring comparison.
Definition helpers.cpp:223
int8_t ilog10(float value)
Compute floor(log10(fabs(value))) using iterative comparison.
Definition helpers.cpp:500
uint32_t fnv1_hash_object_id(const char *str, size_t len)
Calculate FNV-1 hash of a string while applying snake_case + sanitize transformations.
Definition helpers.h:1080
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:160
T clamp_at_least(T value, U min)
Definition helpers.h:2308
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1210
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:1405
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:117
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:588
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:12
size_t size_t pos
Definition helpers.h:1123
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:832
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:1368
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:867
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
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:1443
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:201
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:217
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:257
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:533
char * int8_to_str(char *buf, int8_t val)
Write int8 value to buffer without modulo operations.
Definition helpers.h:1342
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:577
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:357
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:339
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:1469
TemperatureUnit
Definition helpers.h:1688
constexpr uint32_t FNV1_PRIME
FNV-1 32-bit prime.
Definition helpers.h:842
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:929
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:769
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:826
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:126
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:923
const void * src
Definition hal.h:64
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:59
constexpr float celsius_to_fahrenheit(float value)
Convert degrees Celsius to degrees Fahrenheit.
Definition helpers.h:1684
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:915
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:87
size_t size_t const char * fmt
Definition helpers.h:1124
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1305
bool str_startswith(const std::string &str, const std::string &start)
Check whether a string starts with a value.
Definition helpers.cpp:208
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:944
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:1572
int written
Definition helpers.h:1130
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:89
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:1050
constexpr float fahrenheit_to_celsius(float value)
Convert degrees Fahrenheit to degrees Celsius.
Definition helpers.h:1686
uint8_t reverse_bits(uint8_t x)
Reverse the order of 8 bits.
Definition helpers.h:954
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:353
float lerp(float completion, float start, float end)=delete
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:1504
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:821
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:75
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.
bool str_endswith(const std::string &str, const std::string &end)
Check whether a string ends with a value.
Definition helpers.cpp:209
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:890
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:239
uint16_t uint16_t & capacity
Definition helpers.cpp:25
ParseOnOffState
Return values for parse_on_off().
Definition helpers.h:1634
@ PARSE_ON
Definition helpers.h:1636
@ PARSE_TOGGLE
Definition helpers.h:1638
@ PARSE_OFF
Definition helpers.h:1637
@ PARSE_NONE
Definition helpers.h:1635
float pow10_int(int8_t exp)
Compute 10^exp using iterative multiplication/division.
Definition helpers.h:808
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:462
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:1536
static void uint32_t
static Callback create(F &&callable)
Create from any callable.
Definition helpers.h:1720
void call(Ts... args) const
Invoke the callback. Only valid on Callbacks created via create(), never on default-constructed insta...
Definition helpers.h:1716
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
Definition helpers.h:1704
void operator()(T *p) const
Definition helpers.h:2295
Destroys and frees RAMAllocator storage. Not convertible: free() needs the address malloc returned.
Definition helpers.h:2286
void operator()(T *p) const
Definition helpers.h:2287
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