-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitset.cpp
85 lines (68 loc) · 1.59 KB
/
bitset.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "bitset.h"
#include "strings.h"
#include "assert.h"
BitSet::BitSet(){
bytesAlloc = 0;
values = nullptr;
}
BitSet::BitSet(int initialCap){
bytesAlloc = (initialCap + 7) / 8;
if (bytesAlloc > 0){
values = (int*)malloc(((bytesAlloc + 3) / 4) * 4);
}
else{
values = nullptr;
}
}
BitSet::BitSet(const BitSet& orig){
bytesAlloc = orig.bytesAlloc;
if (bytesAlloc > 0){
values = (int*)malloc(((bytesAlloc + 3) / 4) * 4);
MemCpy(values, orig.values, bytesAlloc);
}
else{
values = nullptr;
}
}
BitSet::~BitSet(){
free(values);
values = nullptr;
}
int BitSet::GetBitCapacity() const {
return bytesAlloc * 8;
}
void BitSet::EnsureCapacity(int newCap){
int newBytesAlloc = (newCap + 7) / 8;
if (newBytesAlloc > bytesAlloc){
int* newValues = (int*)malloc(((newBytesAlloc + 3) / 4) * 4);
if (values != nullptr){
MemCpy(newValues, values, newBytesAlloc);
free(values);
}
values = newValues;
bytesAlloc = newBytesAlloc;
}
}
void BitSet::Clear(){
ASSERT(values != nullptr)
MemSet(values, 0, bytesAlloc);
}
bool BitSet::GetBit(int bit) const{
ASSERT(bit / 8 < bytesAlloc);
return GetBitInBitSet(values, bit);
}
void BitSet::SetBit(int bit, bool val){
ASSERT(bit / 8 < bytesAlloc);
SetBitInBitSet(values, bit, val);
}
void SetBitInBitSet(int* vals, int bit, bool val){
int index = (bit / 32);
int bitNum = (bit % 32);
vals[index] = val ? (vals[index] | (1 << bitNum)) : (vals[index] & ~(1 << bitNum));
}
bool GetBitInBitSet(const int* vals, int bit){
int index = (bit / 32);
int bitNum = (bit % 32);
return (vals[index] & (1 << bitNum)) != 0;
}
// TODO: Testing