Skip to content

Commit 1c5d69d

Browse files
committed
Add CircularBufferBlock
WIP: only writes
1 parent 961972f commit 1c5d69d

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include "doctest.h"
2+
3+
#include "util/circular_buffer_block.hh"
4+
5+
TEST_CASE("Basic usage") {
6+
7+
CircularBufferBlock<char, 8> buf;
8+
9+
std::array<char, 6> a{1, 2, 3, 4, 5, 6};
10+
11+
buf.write(a, 0);
12+
CHECK(buf.data[0] == a[0]);
13+
CHECK(buf.data[1] == a[1]);
14+
CHECK(buf.data[2] == a[2]);
15+
CHECK(buf.data[3] == a[3]);
16+
CHECK(buf.data[4] == a[4]);
17+
CHECK(buf.data[5] == a[5]);
18+
19+
std::array<char, 6> b{7, 8, 9, 10, 11, 12};
20+
buf.write(b, 6);
21+
CHECK(buf.data[6] == b[0]);
22+
CHECK(buf.data[7] == b[1]);
23+
CHECK(buf.data[0] == b[2]);
24+
CHECK(buf.data[1] == b[3]);
25+
CHECK(buf.data[2] == b[4]);
26+
CHECK(buf.data[3] == b[5]);
27+
28+
std::array<char, 1> c{99};
29+
buf.write(c, 8);
30+
CHECK(buf.data[0] == 99);
31+
32+
std::array<char, 1> d{88};
33+
buf.write(d, 7);
34+
CHECK(buf.data[7] == 88);
35+
}

util/circular_buffer_block.hh

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#pragma once
2+
#include "util/math.hh"
3+
#include <cstdint>
4+
#include <cstdio>
5+
#include <cstring>
6+
#include <span>
7+
8+
template<typename T, size_t SIZE>
9+
struct CircularBufferBlock {
10+
static_assert(MathTools::is_power_of_2(SIZE));
11+
static constexpr unsigned SIZEMASK = (SIZE - 1);
12+
13+
std::array<T, SIZE> data;
14+
15+
void write(std::span<const T> block, unsigned start_pos) {
16+
unsigned offset = start_pos & SIZEMASK;
17+
auto begin = data.begin() + offset;
18+
19+
if (offset + block.size() <= size()) {
20+
std::memcpy(&*begin, block.data(), block.size());
21+
} else {
22+
int space_avail = size() - offset;
23+
std::memcpy(&*begin, block.data(), space_avail);
24+
std::memcpy(data.data(), block.data() + space_avail, block.size() - space_avail);
25+
}
26+
}
27+
28+
constexpr size_t size() {
29+
return data.size();
30+
}
31+
};

0 commit comments

Comments
 (0)