30 DoubleByteBuffer() { reset(); }
37 memset(buffer_, 0,
sizeof(buffer_));
41 uint8_t * slot(
size_t idx) {
return buffer_[idx]; }
42 const uint8_t * slot(
size_t idx)
const {
return buffer_[idx]; }
44 uint8_t * prepare_write(
int & out_write_idx)
46 K_SPINLOCK(&lock_) { out_write_idx = active_idx_ ^ 1; }
47 return buffer_[out_write_idx];
50 void commit_write(
int write_idx)
52 K_SPINLOCK(&lock_) { active_idx_ = write_idx; }
55 bool write(
const uint8_t * data,
size_t size)
57 if (!data || size > Capacity)
62 uint8_t * dst = prepare_write(write_idx);
63 memcpy(dst, data, size);
64 commit_write(write_idx);
68 bool read_latest(uint8_t * out,
size_t size)
const
70 if (!out || size > Capacity)
74 K_SPINLOCK(&lock_) { memcpy(out, buffer_[active_idx_], size); }
78 static constexpr size_t capacity() {
return Capacity; }
80 [[nodiscard]]
int active_index()
const
83 K_SPINLOCK(&lock_) { idx = active_idx_; }
88 uint8_t buffer_[2][Capacity]{};
89 mutable struct k_spinlock lock_{};
97 DoubleBuffer() { reset(); }
109 T & slot(
size_t idx) {
return slots_[idx]; }
110 const T & slot(
size_t idx)
const {
return slots_[idx]; }
112 T & prepare_write(
int & out_write_idx)
114 K_SPINLOCK(&lock_) { out_write_idx = active_idx_ ^ 1; }
115 return slots_[out_write_idx];
118 void commit_write(
int write_idx)
120 K_SPINLOCK(&lock_) { active_idx_ = write_idx; }
123 void write(
const T & value)
126 prepare_write(write_idx) = value;
127 commit_write(write_idx);
130 bool read_latest(T & out)
const
132 K_SPINLOCK(&lock_) { out = slots_[active_idx_]; }
136 [[nodiscard]]
int active_index()
const
139 K_SPINLOCK(&lock_) { idx = active_idx_; }
145 mutable struct k_spinlock lock_{};