-
Notifications
You must be signed in to change notification settings - Fork 31
/
progressivebuffer.h
61 lines (57 loc) · 1.38 KB
/
progressivebuffer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Copyright (c) 2019-2024, Edoardo Lolletti (edo9300) <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#ifndef PROGRESSIVEBUFFER_H_
#define PROGRESSIVEBUFFER_H_
#include <cstdint>
#include <cstring> //std::memcpy
#include <vector>
class ProgressiveBuffer {
public:
std::vector<uint8_t> data;
void clear() {
data.clear();
}
template<class T>
T at(const size_t pos) const {
static constexpr auto valsize = sizeof(T);
size_t size = (pos + 1) * valsize;
T ret{};
if(data.size() < size)
return ret;
std::memcpy(&ret, data.data() + pos * valsize, sizeof(T));
return ret;
}
template<class T>
void set(const size_t pos, T val) {
static constexpr auto valsize = sizeof(T);
size_t size = (pos + 1) * valsize;
if(data.size() < size)
data.resize(size);
std::memcpy(data.data() + pos * valsize, &val, sizeof(T));
}
bool bitGet(const size_t pos) const {
size_t real_pos = pos / 8u;
uint32_t index = pos % 8u;
size_t size = real_pos + 1;
if(data.size() < size)
return false;
return !!(data[real_pos] & (1 << index));
}
void bitToggle(const size_t pos, bool set) {
size_t real_pos = pos / 8u;
uint32_t index = pos % 8u;
size_t size = real_pos + 1;
if(data.size() < size) {
data.resize(size);
}
if(set)
data[real_pos] |= (1 << index);
else {
data[real_pos] &= ~(1 << index);
}
}
};
#endif /* PROGRESSIVEBUFFER_H_ */