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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use serde::{de::Error, Deserialize, Deserializer, Serialize};
use std::ops::BitAnd;
#[cfg(any(test, feature = "fuzzing"))]
use proptest_derive::Arbitrary;
const BUCKET_SIZE: usize = 8;
const MAX_BUCKETS: usize = 32;
#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub struct BitVec {
#[serde(with = "serde_bytes")]
inner: Vec<u8>,
}
impl BitVec {
#[allow(dead_code)]
pub fn set(&mut self, pos: u8) {
let bucket: usize = pos as usize / BUCKET_SIZE;
if self.inner.len() <= bucket {
self.inner.resize(bucket + 1, 0);
}
let bucket_pos = pos as usize - (bucket * BUCKET_SIZE);
self.inner[bucket] |= 0b1000_0000 >> bucket_pos as u8;
}
#[allow(dead_code)]
pub fn is_set(&self, pos: u8) -> bool {
let bucket: usize = pos as usize / BUCKET_SIZE;
if self.inner.len() <= bucket {
return false;
}
let bucket_pos = pos as usize - (bucket * BUCKET_SIZE);
(self.inner[bucket] & (0b1000_0000 >> bucket_pos as u8)) != 0
}
#[allow(dead_code)]
pub fn count_ones(&self) -> u32 {
self.inner.iter().map(|a| a.count_ones()).sum()
}
#[allow(dead_code)]
pub fn last_set_bit(&self) -> Option<u8> {
self.inner
.iter()
.rev()
.enumerate()
.find(|(_, byte)| byte != &&0u8)
.map(|(i, byte)| {
(8 * (self.inner.len() - i) - byte.trailing_zeros() as usize - 1) as u8
})
}
}
impl BitAnd for BitVec {
type Output = BitVec;
fn bitand(self, other: Self) -> Self {
let len = std::cmp::min(self.inner.len(), other.inner.len());
let mut ret = BitVec {
inner: Vec::with_capacity(len),
};
for i in 0..len {
ret.inner.push(self.inner[i] & other.inner[i]);
}
ret
}
}
impl<'de> Deserialize<'de> for BitVec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let v = serde_bytes::ByteBuf::deserialize(deserializer)?.into_vec();
if v.len() > MAX_BUCKETS {
return Err(D::Error::custom(format!("BitVec too long: {}", v.len())));
}
Ok(BitVec { inner: v })
}
}
#[cfg(test)]
mod test {
use super::*;
use proptest::{arbitrary::any, collection::vec, prelude::*};
#[test]
fn test_count_ones() {
let p0 = BitVec::default();
assert_eq!(p0.count_ones(), 0);
let p1 = BitVec {
inner: vec![7u8, 15u8],
};
assert_eq!(p1.count_ones(), 7);
let p2 = BitVec {
inner: vec![7u8; MAX_BUCKETS],
};
assert_eq!(p2.count_ones(), 3 * MAX_BUCKETS as u32);
let p3 = BitVec {
inner: vec![255u8; MAX_BUCKETS],
};
assert_eq!(p3.count_ones(), 8 * MAX_BUCKETS as u32);
let p4 = BitVec {
inner: vec![0u8; MAX_BUCKETS],
};
assert_eq!(p4.count_ones(), 0);
}
#[test]
fn test_last_set_bit() {
let p0 = BitVec::default();
assert_eq!(p0.last_set_bit(), None);
let p1 = BitVec { inner: vec![224u8] };
assert_eq!(p1.inner.len(), 1);
assert_eq!(p1.last_set_bit(), Some(2));
let p2 = BitVec {
inner: vec![7u8, 128u8],
};
assert_eq!(p2.inner.len(), 2);
assert_eq!(p2.last_set_bit(), Some(8));
let p3 = BitVec {
inner: vec![255u8; MAX_BUCKETS],
};
assert_eq!(p3.inner.len(), MAX_BUCKETS);
assert_eq!(p3.last_set_bit(), Some(255));
let p4 = BitVec {
inner: vec![0u8; MAX_BUCKETS],
};
assert_eq!(p4.last_set_bit(), None);
let mut p5 = BitVec {
inner: vec![0b0000_0001, 0b0100_0000],
};
assert_eq!(p5.last_set_bit(), Some(9));
assert!(p5.is_set(7));
assert!(p5.is_set(9));
assert!(!p5.is_set(0));
p5.set(10);
assert!(p5.is_set(10));
assert_eq!(p5.last_set_bit(), Some(10));
assert_eq!(p5.inner, vec![0b0000_0001, 0b0110_0000]);
let p6 = BitVec {
inner: vec![0b1000_0000],
};
assert_eq!(p6.inner.len(), 1);
assert_eq!(p6.last_set_bit(), Some(0));
}
#[test]
fn test_empty() {
let p = BitVec::default();
for i in 0..=std::u8::MAX {
assert_eq!(false, p.is_set(i));
}
}
#[test]
fn test_extremes() {
let mut p = BitVec::default();
p.set(std::u8::MAX);
p.set(0);
assert!(p.is_set(std::u8::MAX));
assert!(p.is_set(0));
for i in 1..std::u8::MAX {
assert_eq!(false, p.is_set(i));
}
}
#[test]
fn test_deserialization() {
let mut bytes = [0u8; 47];
bytes[0] = 46;
assert!(bcs::from_bytes::<Vec<u8>>(&bytes).is_ok());
assert!(bcs::from_bytes::<BitVec>(&bytes).is_err());
let mut bytes = [0u8; 33];
bytes[0] = 32;
let bv = BitVec {
inner: Vec::from([0u8; 32].as_ref()),
};
assert_eq!(Ok(bv), bcs::from_bytes::<BitVec>(&bytes));
}
fn construct_bitvec(posns: &[u8]) -> BitVec {
let mut bv = BitVec::default();
posns.iter().for_each(|x| bv.set(*x));
bv
}
proptest! {
#[test]
fn test_arbitrary(mut v in vec(any::<u8>(), 0..256)) {
let bv = construct_bitvec(&v);
v.sort_unstable();
v.dedup();
let mut viter = v.into_iter().peekable();
for i in 0..std::u8::MAX {
if viter.peek() == Some(&i) {
prop_assert!(bv.is_set(i));
viter.next();
} else {
prop_assert_eq!(false, bv.is_set(i));
}
}
}
}
proptest! {
#[test]
fn test_and(v1 in vec(any::<u8>(), 0..256), v2 in vec(any::<u8>(), 0..256)) {
let bv1 = construct_bitvec(&v1);
let bv2 = construct_bitvec(&v2);
let intersection = bv1.clone() & bv2.clone();
for i in 0..std::u8::MAX {
if bv1.is_set(i) && bv2.is_set(i) {
prop_assert!(intersection.is_set(i));
} else {
prop_assert_eq!(false, intersection.is_set(i));
}
}
}
}
}