-
Notifications
You must be signed in to change notification settings - Fork 8
/
bitpair_vector.hpp
99 lines (79 loc) · 2.53 KB
/
bitpair_vector.hpp
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
#pragma once
#include <xmmintrin.h>
namespace emphf {
class bitpair_vector {
public:
bitpair_vector()
: m_size(0)
{}
bitpair_vector(uint64_t n)
: m_size(0)
{
resize(n);
}
void resize(uint64_t n)
{
// can only grow, for now
assert(n >= size());
m_size = n;
m_bits.resize((m_size + 31) / 32);
}
size_t size() const
{
return m_size;
}
uint64_t operator[](uint64_t pos) const
{
return (m_bits[pos / 32] >> ((pos % 32) * 2)) % 4;
}
void set(uint64_t pos, uint64_t val)
{
assert(val < 4);
uint64_t word_pos = pos / 32;
uint64_t word_offset = (pos % 32) * 2;
m_bits[word_pos] &= ~(3ULL << word_offset);
m_bits[word_pos] |= val << word_offset;
}
uint64_t range_nonzeros(uint64_t begin, uint64_t end) const
{
assert(begin <= end);
assert(end <= size());
uint64_t word_begin = begin / 32;
uint64_t offset_begin = (begin % 32) * 2;
uint64_t word_end = end / 32;
uint64_t offset_end = (end % 32) * 2;
uint64_t r = 0;
uint64_t word = (m_bits[word_begin] >> offset_begin) << offset_begin;
for (uint64_t w = word_begin; w < word_end; ++w) {
r += nonzero_pairs(word);
word = m_bits[w + 1];
}
uint64_t mask = (uint64_t(1) << offset_end) - 1;
r += nonzero_pairs(word & mask);
return r;
}
void swap(bitpair_vector& other)
{
std::swap(m_size, other.m_size);
m_bits.swap(other.m_bits);
}
void save(std::ostream& os) const
{
os.write(reinterpret_cast<char const*>(&m_size), sizeof(m_size));
os.write(reinterpret_cast<char const*>(m_bits.data()), (std::streamsize)(sizeof(m_bits[0]) * m_bits.size()));
}
void load(std::istream& is)
{
is.read(reinterpret_cast<char*>(&m_size), sizeof(m_size));
m_bits.resize((m_size + 31) / 32);
is.read(reinterpret_cast<char*>(m_bits.data()), (std::streamsize)(sizeof(m_bits[0]) * m_bits.size()));
}
std::vector<uint64_t> const& data() const
{
return m_bits;
}
protected:
std::vector<uint64_t> m_bits;
uint64_t m_size;
};
}