ESPHome 2026.4.0-dev
Loading...
Searching...
No Matches
api_buffer.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <cstring>
5#include <memory>
6
9
10namespace esphome::api {
11
14inline std::unique_ptr<uint8_t[]> make_buffer(size_t n) {
15#if defined(USE_ESP8266) || defined(USE_LIBRETINY)
16 return std::make_unique<uint8_t[]>(n);
17#else
18 return std::make_unique_for_overwrite<uint8_t[]>(n);
19#endif
20}
21
36class APIBuffer {
37 public:
38 void clear() { this->size_ = 0; }
39 inline void reserve(size_t n) ESPHOME_ALWAYS_INLINE {
40 if (n > this->capacity_)
41 this->grow_(n);
42 }
43 inline void resize(size_t n) ESPHOME_ALWAYS_INLINE {
44 this->reserve(n);
45 this->size_ = n; // no zero-fill
46 }
49 inline void reserve_and_resize(size_t reserve_size, size_t new_size) ESPHOME_ALWAYS_INLINE {
50 this->reserve(std::max(reserve_size, new_size));
51 this->size_ = new_size;
52 }
53 uint8_t *data() { return this->data_.get(); }
54 const uint8_t *data() const { return this->data_.get(); }
55 size_t size() const { return this->size_; }
56 bool empty() const { return this->size_ == 0; }
57 uint8_t &operator[](size_t i) { return this->data_[i]; }
58 const uint8_t &operator[](size_t i) const { return this->data_[i]; }
60 void release() {
61 this->data_.reset();
62 this->size_ = 0;
63 this->capacity_ = 0;
64 }
65
66 protected:
67 void grow_(size_t n);
68 std::unique_ptr<uint8_t[]> data_;
69 size_t size_{0};
70 size_t capacity_{0};
71};
72
73} // namespace esphome::api
Byte buffer that skips zero-initialization on resize().
Definition api_buffer.h:36
const uint8_t * data() const
Definition api_buffer.h:54
void reserve(size_t n) ESPHOME_ALWAYS_INLINE
Definition api_buffer.h:39
void grow_(size_t n)
Definition api_buffer.cpp:5
void release()
Release all memory (equivalent to std::vector swap trick).
Definition api_buffer.h:60
const uint8_t & operator[](size_t i) const
Definition api_buffer.h:58
void reserve_and_resize(size_t reserve_size, size_t new_size) ESPHOME_ALWAYS_INLINE
Reserve capacity for max(reserve_size, new_size) bytes, then set size to new_size.
Definition api_buffer.h:49
size_t size() const
Definition api_buffer.h:55
uint8_t & operator[](size_t i)
Definition api_buffer.h:57
void resize(size_t n) ESPHOME_ALWAYS_INLINE
Definition api_buffer.h:43
std::unique_ptr< uint8_t[]> data_
Definition api_buffer.h:68
std::unique_ptr< uint8_t[]> make_buffer(size_t n)
Helper to use make_unique_for_overwrite where available (skips zero-fill), falling back to make_uniqu...
Definition api_buffer.h:14