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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#[cfg(test)] mod tests;
use std::iter::FromIterator;
pub type Id = usize;
type Block = u32;
const BITS: usize = 32;
fn num_blocks(bits: usize) -> usize {
if bits % BITS == 0 {
bits / BITS
} else {
bits / BITS + 1
}
}
pub struct IdSet {
storage: Vec<Block>,
len: usize,
}
impl IdSet {
pub fn new() -> Self {
IdSet {
storage: Vec::new(),
len: 0,
}
}
pub fn with_capacity(nbits: usize) -> Self {
IdSet {
storage: Vec::with_capacity(num_blocks(nbits)),
len: 0,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn insert(&mut self, id: Id) -> bool {
let (word, bit) = (id / BITS, id % BITS);
let mask = 1 << bit;
if word < self.storage.len() {
if (self.storage[word] & mask) == 0 {
self.storage[word] |= mask;
self.len += 1;
true
} else {
false
}
} else {
self.storage.resize(word + 1, 0);
self.storage[word] = mask;
self.len += 1;
true
}
}
pub fn remove(&mut self, id: Id) -> bool {
let (word, bit) = (id / BITS, id % BITS);
let mask = 1 << bit;
if word < self.storage.len() {
if (self.storage[word] & mask) != 0 {
self.storage[word] &= !mask;
self.len -= 1;
true
} else {
false
}
} else {
false
}
}
pub fn contains(&self, id: Id) -> bool {
let (word, bit) = (id / BITS, id % BITS);
let mask = 1 << bit;
if word < self.storage.len() {
(self.storage[word] & mask) != 0
} else {
false
}
}
pub fn iter(&self) -> Iter {
Iter {
storage: &self.storage,
word: 0,
bit: 0,
}
}
}
impl FromIterator<Id> for IdSet {
fn from_iter<I: IntoIterator<Item = Id>>(iter: I) -> Self {
let mut set = IdSet::new();
for id in iter {
set.insert(id);
}
set
}
}
impl<'a> IntoIterator for &'a IdSet {
type Item = Id;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
pub struct Iter<'a> {
storage: &'a [u32],
word: usize,
bit: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = Id;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.bit == BITS {
self.word += 1;
if self.word >= self.storage.len() {
return None;
}
self.bit = 0;
}
let bit = self.bit;
self.bit += 1;
if (self.storage[self.word] & (1 << bit)) != 0 {
return Some(self.word * BITS + bit)
}
}
}
}