ESPHome 2026.3.0
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 }
47 uint8_t *data() { return this->data_.get(); }
48 const uint8_t *data() const { return this->data_.get(); }
49 size_t size() const { return this->size_; }
50 bool empty() const { return this->size_ == 0; }
51 uint8_t &operator[](size_t i) { return this->data_[i]; }
52 const uint8_t &operator[](size_t i) const { return this->data_[i]; }
54 void release() {
55 this->data_.reset();
56 this->size_ = 0;
57 this->capacity_ = 0;
58 }
59
60 protected:
61 void grow_(size_t n);
62 std::unique_ptr<uint8_t[]> data_;
63 size_t size_{0};
64 size_t capacity_{0};
65};
66
67} // 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:48
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:54
const uint8_t & operator[](size_t i) const
Definition api_buffer.h:52
size_t size() const
Definition api_buffer.h:49
uint8_t & operator[](size_t i)
Definition api_buffer.h:51
void resize(size_t n) ESPHOME_ALWAYS_INLINE
Definition api_buffer.h:43
std::unique_ptr< uint8_t[]> data_
Definition api_buffer.h:62
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