Skip to content

Commit cbf17eb

Browse files
committed
Unify bitset.hpp implementation with the one in Spring.
1 parent 5f76c08 commit cbf17eb

File tree

1 file changed

+65
-1
lines changed

1 file changed

+65
-1
lines changed

libraries/eosiolib/core/eosio/bitset.hpp

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ struct bitset {
3636

3737
size_type size() const { return m_num_bits; }
3838

39-
size_type num_blocks() const { return m_bits.size(); }
39+
size_type num_blocks() const {
40+
assert(m_bits.size() == calc_num_blocks(m_num_bits));
41+
return m_bits.size();
42+
}
4043

4144
void resize(size_type num_bits) {
4245
m_bits.resize(calc_num_blocks(num_bits), 0);
@@ -54,16 +57,56 @@ struct bitset {
5457
m_bits[block_index(pos)] &= ~bit_mask(pos);
5558
}
5659

60+
bool test(size_type pos) const {
61+
return (*this)[pos];
62+
}
63+
5764
bool operator[](size_type pos) const {
5865
assert(pos < m_num_bits);
5966
return !!(m_bits[block_index(pos)] & bit_mask(pos));
6067
}
6168

69+
void flip(size_type pos) {
70+
assert(pos < m_num_bits);
71+
if (test(pos))
72+
clear(pos);
73+
else
74+
set(pos);
75+
}
76+
77+
void flip() {
78+
for (auto& byte : m_bits)
79+
byte = ~byte;
80+
zero_unused_bits();
81+
}
82+
83+
bool all() const {
84+
auto sz = size();
85+
for (size_t i=0; i<sz; ++i)
86+
if (!test(i))
87+
return false;
88+
return true;
89+
}
90+
91+
bool none() const {
92+
for (auto& byte : m_bits)
93+
if (byte)
94+
return false;
95+
return true;
96+
}
97+
6298
void zero_all_bits() {
6399
for (auto& byte : m_bits)
64100
byte = 0;
65101
}
66102

103+
bitset operator|=(const bitset& o) {
104+
assert(size() == o.size());
105+
for (size_t i=0; i<m_bits.size(); ++i)
106+
m_bits[i] |= o.m_bits[i];
107+
return *this;
108+
}
109+
67110
void zero_unused_bits() {
68111
assert (m_bits.size() == calc_num_blocks(m_num_bits));
69112

@@ -107,6 +150,27 @@ struct bitset {
107150
return res;
108151
}
109152

153+
static bitset from_string(std::string_view s) {
154+
bitset bs;
155+
auto num_bits = s.size();
156+
bs.resize(num_bits);
157+
158+
for (size_t i = 0; i < num_bits; ++i) {
159+
switch (s[i]) {
160+
case '0':
161+
break; // nothing to do, all bits initially 0
162+
case '1':
163+
bs.set(num_bits - i - 1); // high bitset indexes come first in the JSON representation
164+
break;
165+
default:
166+
throw std::invalid_argument( "unexpected character in bitset string representation" );
167+
break;
168+
}
169+
}
170+
assert(bs.unused_bits_zeroed());
171+
return bs;
172+
}
173+
110174
void print() const {
111175
auto s = to_string();
112176
if (!s.empty())

0 commit comments

Comments
 (0)