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
use std::ops::Index;
static TRUE: bool = true;
static FALSE: bool = false;
const BITS: usize = 32;
type Block = u32;
#[inline]
fn div_rem(x: usize, d: usize) -> (usize, usize)
{
(x / d, x % d)
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FixedBitSet {
data: Box<[Block]>,
length: usize,
}
impl FixedBitSet
{
pub fn with_capacity(bits: usize) -> Self
{
let (mut blocks, rem) = div_rem(bits, BITS);
blocks += (rem > 0) as usize;
let mut data = Vec::with_capacity(blocks);
unsafe {
data.set_len(blocks);
for elt in &mut data {
*elt = 0;
}
}
FixedBitSet {
data: data.into_boxed_slice(),
length: bits,
}
}
pub fn len(&self) -> usize { self.length }
#[inline]
pub fn contains(&self, bit: usize) -> bool
{
let (block, i) = div_rem(bit, BITS);
match self.data.get(block) {
None => false,
Some(b) => (b & (1 << i)) != 0,
}
}
#[inline]
pub fn clear(&mut self)
{
for elt in &mut self.data[..] {
*elt = 0
}
}
#[inline]
pub fn insert(&mut self, bit: usize)
{
assert!(bit < self.length);
let (block, i) = div_rem(bit, BITS);
unsafe {
*self.data.get_unchecked_mut(block) |= 1 << i;
}
}
#[inline]
pub fn set(&mut self, bit: usize, enabled: bool)
{
assert!(bit < self.length);
let (block, i) = div_rem(bit, BITS);
unsafe {
let elt = self.data.get_unchecked_mut(block);
if enabled {
*elt |= 1 << i;
} else {
*elt &= !(1 << i);
}
}
}
}
impl Clone for FixedBitSet
{
fn clone(&self) -> Self
{
FixedBitSet {
data: self.data.to_vec().into_boxed_slice(),
length: self.length,
}
}
}
impl Index<usize> for FixedBitSet
{
type Output = bool;
#[inline]
fn index(&self, bit: usize) -> &bool
{
if self.contains(bit) {
&TRUE
} else {
&FALSE
}
}
}
#[test]
fn it_works() {
let N = 50;
let mut fb = FixedBitSet::with_capacity(N);
println!("{:?}", fb);
for i in 0..(N + 10) {
assert_eq!(fb.contains(i), false);
}
fb.insert(10);
fb.set(11, false);
fb.set(12, false);
fb.set(12, true);
fb.set(N-1, true);
println!("{:?}", fb);
assert!(fb.contains(10));
assert!(!fb.contains(11));
assert!(fb.contains(12));
assert!(fb.contains(N-1));
for i in 0..N {
let contain = i == 10 || i == 12 || i == N - 1;
assert_eq!(contain, fb[i]);
}
fb.clear();
}