-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitRowBuilder.cpp
122 lines (106 loc) · 1.97 KB
/
BitRowBuilder.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "BitRowBuilder.h"
#ifdef _MSC_VER
#include <intrin.h>
typedef unsigned long DWORD;
#endif
BitRowBuilder::BitRowBuilder()
{
row = EMPTYROW;
}
BitRowBuilder::BitRowBuilder(int r)
{
row = r;
lenDirty = true;
}
int BitRowBuilder::getRow()
{
return row;
}
void BitRowBuilder::reset()
{
row = EMPTYROW;
}
BitRowBuilder& BitRowBuilder::add(bool isEmpty)
{
row <<= 1;
row ^= (isEmpty ? 0 : 1);
lenDirty = true;
return (*this);
}
BitRowBuilder & BitRowBuilder::add(int b)
{
row <<= 1;
row ^= b;
lenDirty = true;
return (*this);
}
int BitRowBuilder::length()
{
if (lenDirty) {
len = LengthOf(row);
}
return len;
}
void BitRowBuilder::inplaceReverse()
{
row = GetReverse(row);
}
bool BitRowBuilder::isSet(int idx)
{
return (row & (1 << (length() - 1 - idx))) != 0;
}
bool BitRowBuilder::IsSet(int someRow, int idx)
{
return (someRow & (1 << (LengthOf(someRow) - 1 - idx))) != 0;
}
int BitRowBuilder::RowSplice(int someRow, int idx)
{
int startLen = LengthOf(someRow);
someRow &= ~(1 << startLen);
for (int i = 0; i < idx; i++) {
someRow &= ~(1 << (startLen - 1 - i));
}
someRow |= 1 << (startLen - idx);
return someRow;
}
bool BitRowBuilder::RowStartsWith(int someRow, int p)
{
int len1 = LengthOf(someRow) + 1;
int len2 = LengthOf(p) + 1;
if (len1 < len2)
return false;
return (someRow >> (len1 - len2)) == p;
}
int BitRowBuilder::GetReverse(int someRow)
{
int rlen = LengthOf(someRow);
int backwardRow = EMPTYROW;
for (int i = 0; i < rlen; i++) {
if ((someRow & (1 << i)) != 0) {
backwardRow = (backwardRow << 1) ^ 1;
}
else {
backwardRow = (backwardRow << 1);
}
}
return backwardRow;
}
int BitRowBuilder::LengthOf(int anotherRow)
{
if (anotherRow == 0)
return 0;
int minToOne = 0;
#ifdef _MSC_VER
DWORD leadingZero = 0;
_BitScanReverse(&leadingZero, anotherRow);
minToOne = leadingZero;
#elif __GNUC__
minToOne = 31 - __builtin_clz(anotherRow);
#else
int v = anotherRow;
while (v >>= 1) {
minToOne++;
}
#endif
return minToOne;
}