ESPHome 2026.9.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
26class APIBuffer {
27 public:
28 void clear() { this->size_ = 0; }
30 [[nodiscard]] inline bool reserve(size_t n) ESPHOME_ALWAYS_INLINE { return n <= this->capacity_ || this->grow_(n); }
32 [[nodiscard]] inline bool resize(size_t n) ESPHOME_ALWAYS_INLINE { return this->reserve_and_resize(n, n); }
36 [[nodiscard]] inline bool reserve_and_resize(size_t reserve_size, size_t new_size) ESPHOME_ALWAYS_INLINE {
37 if (!this->reserve(std::max(reserve_size, new_size)))
38 return false;
39 this->size_ = new_size;
40 return true;
41 }
42 uint8_t *data() { return this->data_.get(); }
43 const uint8_t *data() const { return this->data_.get(); }
44 size_t size() const { return this->size_; }
45 size_t capacity() const { return this->capacity_; }
46 bool empty() const { return this->size_ == 0; }
47 uint8_t &operator[](size_t i) { return this->data_[i]; }
48 const uint8_t &operator[](size_t i) const { return this->data_[i]; }
50 void release() {
51 this->data_.reset();
52 this->size_ = 0;
53 this->capacity_ = 0;
54 }
55
56 protected:
57 bool grow_(size_t n);
58 std::unique_ptr<uint8_t[]> data_;
59 size_t size_{0};
60 size_t capacity_{0};
61};
62
63} // namespace esphome::api
Byte buffer that skips zero-initialization on resize().
Definition api_buffer.h:26
const uint8_t * data() const
Definition api_buffer.h:43
bool grow_(size_t n)
Definition api_buffer.cpp:6
void release()
Release all memory (equivalent to std::vector swap trick).
Definition api_buffer.h:50
const uint8_t & operator[](size_t i) const
Definition api_buffer.h:48
size_t size() const
Definition api_buffer.h:44
uint8_t & operator[](size_t i)
Definition api_buffer.h:47
size_t capacity() const
Definition api_buffer.h:45
bool reserve(size_t n) ESPHOME_ALWAYS_INLINE
Returns false if allocation fails; the buffer is left unchanged.
Definition api_buffer.h:30
std::unique_ptr< uint8_t[]> data_
Definition api_buffer.h:58
bool resize(size_t n) ESPHOME_ALWAYS_INLINE
Returns false if allocation fails; the buffer is left unchanged. No zero-fill.
Definition api_buffer.h:32
bool 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:36