arduino-audio-tools
All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends Modules Pages
BitVector.h
1#pragma once
2#ifdef HAS_IOSTRAM
3#include "Vector.h"
4#include <stdint.h>
5#include <iostream>
6
7namespace audio_tools {
8
15class BitVector {
16public:
17 BitVector() = default;
18 BitVector(int size) {
19 resize(size);
20 }
21
22 inline bool operator[](size_t index) { return get(index); }
23
24 bool get(int64_t index) {
25 if (index < 0)
26 return false;
27 bool result = false;
28 int offset = index / sizeof(uint64_t);
29 int bit = index % sizeof(uint64_t);
30 if (offset < vector.size()) {
31 uint64_t value = vector[offset];
32 // get bit
33 result = (value >> bit) & 1U;
34 }
35 return result;
36 }
37
38 void set(int64_t index, bool value) {
39 if (index < 0)
40 return;
41 max_idx = max(max_idx, index + 1);
42 int offset = index / sizeof(uint64_t);
43 int bit = index % sizeof(uint64_t);
44 while (offset >= vector.size()) {
45 vector.push_back(0l);
46 }
47 // check if we need to updte the value
48 if (((vector[offset] >> bit) & 1U) != value) {
49 // needs update
50 if (value) {
51 // set bit
52 vector[offset] |= 1UL << bit;
53 } else {
54 // clear bit
55 vector[offset] &= ~(1UL << bit);
56 }
57 // call change handler to notify about change
58 if (changeHandler != nullptr) {
59 changeHandler(index, value, ref);
60 }
61 }
62 }
63
64 void clear() {
65 max_idx = 0;
66 vector.clear();
67 vector.shrink_to_fit();
68 }
69
70 int size() { return max_idx; }
71
73 void setChangeCallback(void (*hdler)(int idx, bool value, void *ref),
74 void *ref = nullptr) {
75 changeHandler = hdler;
76 this->ref = ref;
77 }
78
80 void resize(int size) {
81 max_idx = size;
82 int round_up = size % 64 != 0;
83 vector.resize(size / 64 + round_up);
84 for (int j=0;j<max_idx;j++){
85 set(j, 0);
86 }
87 }
88
89 // shifts n bits: + to the right; - to the left
90 void shift(int n) {
91 if (n == 0)
92 return;
93 for (int j = 0; j < max_idx - n; j++) {
94 set(j, get(j - n));
95 }
96 max_idx+=n;
97 }
99 template <typename T> T toInt(int n) {
100 T result;
101 for (int j = 0; j < sizeof(T) * 8; j++) {
102 bool x = get(n);
103 // set bit at pos
104 result ^= (-x ^ result) & (1UL << j);
105 }
106 return result;
107 }
108
109
110protected:
111 Vector<uint64_t> vector;
112 void (*changeHandler)(int idx, bool value, void *ref) = nullptr;
113 void *ref;
114 int64_t max_idx = 0;
115};
116
117
118} // namespace audio_tools
119
120#endif
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition AudioCodecsBase.h:10