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
use std::fmt::{Debug, Error, Formatter};
use crate::types::Bits;
pub struct Bitmap<Size: Bits> {
data: Size::Store,
}
impl<Size: Bits> Clone for Bitmap<Size> {
fn clone(&self) -> Self {
Bitmap { data: self.data }
}
}
impl<Size: Bits> Copy for Bitmap<Size> {}
impl<Size: Bits> Default for Bitmap<Size> {
fn default() -> Self {
Bitmap {
data: Size::Store::default(),
}
}
}
impl<Size: Bits> PartialEq for Bitmap<Size> {
fn eq(&self, other: &Self) -> bool {
self.data == other.data
}
}
impl<Size: Bits> Debug for Bitmap<Size> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.data.fmt(f)
}
}
impl<Size: Bits> Bitmap<Size> {
#[inline]
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn len(self) -> usize {
Size::len(&self.data)
}
#[inline]
pub fn is_empty(self) -> bool {
self.first_index().is_none()
}
#[inline]
pub fn get(self, index: usize) -> bool {
Size::get(&self.data, index)
}
#[inline]
pub fn set(&mut self, index: usize, value: bool) -> bool {
Size::set(&mut self.data, index, value)
}
#[inline]
pub fn first_index(self) -> Option<usize> {
Size::first_index(&self.data)
}
}
impl<Size: Bits> IntoIterator for Bitmap<Size> {
type Item = usize;
type IntoIter = Iter<Size>;
fn into_iter(self) -> Self::IntoIter {
Iter {
index: 0,
data: self.data,
}
}
}
pub struct Iter<Size: Bits> {
index: usize,
data: Size::Store,
}
impl<Size: Bits> Iterator for Iter<Size> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= Size::USIZE {
return None;
}
if Size::get(&self.data, self.index) {
self.index += 1;
Some(self.index - 1)
} else {
self.index += 1;
self.next()
}
}
}
#[cfg(test)]
mod test {
use super::*;
use proptest::collection::btree_set;
use proptest::proptest;
use typenum::U64;
proptest! {
#[test]
fn get_set_and_iter(bits in btree_set(0..64usize, 0..64)) {
let mut bitmap = Bitmap::<U64>::new();
for i in &bits {
bitmap.set(*i, true);
}
for i in 0..64 {
assert_eq!(bitmap.get(i), bits.contains(&i));
}
assert!(bitmap.into_iter().eq(bits.into_iter()));
}
}
}