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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// SPDX-License-Identifier: MPL-2.0

#![allow(unused_variables)]

use core::{
    fmt::{self},
    sync::atomic::{AtomicU64, Ordering::Relaxed},
};

use align_ext::AlignExt;

use crate::prelude::*;

/// A fixed number of bits taht can be safely shared between threads.
pub struct AtomicBits {
    num_bits: usize,
    u64s: Box<[AtomicU64]>,
}

impl AtomicBits {
    /// Creates a given number of bit 0s.
    pub fn new_zeroes(num_bits: usize) -> Self {
        Self::new(0, num_bits)
    }

    /// Creates a given number of bit 1s.
    pub fn new_ones(num_bits: usize) -> Self {
        Self::new(!0, num_bits)
    }

    fn new(u64_val: u64, num_bits: usize) -> Self {
        let num_u64s = num_bits.align_up(64) / 64;
        let u64s = {
            let mut u64s = Vec::with_capacity(num_u64s);
            for _ in 0..num_u64s {
                u64s.push(AtomicU64::new(u64_val));
            }
            u64s.into_boxed_slice()
        };
        Self { num_bits, u64s }
    }

    /// Returns the length in bits.
    pub fn len(&self) -> usize {
        self.num_bits
    }

    /// Gets the bit at a given position.
    pub fn get(&self, index: usize) -> bool {
        assert!(index < self.num_bits);
        let i = index / 64;
        let j = index % 64;
        // SAFETY: Variable i is in range as variable index is in range.
        let u64_atomic = unsafe { self.u64s.get_unchecked(i) };
        (u64_atomic.load(Relaxed) & 1 << j) != 0
    }

    /// Sets the bit at a given position.
    pub fn set(&self, index: usize, new_bit: bool) {
        assert!(index < self.num_bits);
        let i = index / 64;
        let j = index % 64;
        // SAFETY: Variable i is in range as variable index is in range.
        let u64_atomic = unsafe { self.u64s.get_unchecked(i) };
        if new_bit {
            u64_atomic.fetch_or(1 << j, Relaxed);
        } else {
            u64_atomic.fetch_and(!(1 << j), Relaxed);
        }
    }

    /// Clears all the bits.
    pub fn clear(&self) {
        todo!()
    }

    /// Are all bits ones.
    pub fn is_full(&self) -> bool {
        self.match_pattern(!0)
    }

    /// Are all bits zeroes.
    pub fn is_empty(&self) -> bool {
        self.match_pattern(0)
    }

    fn match_pattern(&self, pattern: u64) -> bool {
        todo!()
    }

    /// Gets an iterator for the bits.
    pub fn iter(&self) -> Iter<'_> {
        Iter::new(self)
    }

    /// Gets an iterator that gives the positions of all 1s in the bits.
    pub fn iter_ones(&self) -> OnesIter<'_> {
        OnesIter::new(self)
    }

    /// Gets an iterator that gives the positions of all 0s in the bits.
    pub fn iter_zeroes(&self) -> ZeroesIter<'_> {
        ZeroesIter::new(self)
    }
}

/// An iterator that accesses the bits of an `AtomicBits`.
pub struct Iter<'a> {
    bits: &'a AtomicBits,
    bit_i: usize,
}

impl<'a> Iter<'a> {
    fn new(bits: &'a AtomicBits) -> Self {
        Self { bits, bit_i: 0 }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = bool;

    fn next(&mut self) -> Option<bool> {
        if self.bit_i < self.bits.len() {
            let bit = self.bits.get(self.bit_i);
            self.bit_i += 1;
            Some(bit)
        } else {
            None
        }
    }
}

/// An iterator that returns the positions of 1s in an [`AtomicBits`].
pub struct OnesIter<'a> {
    bits: &'a AtomicBits,
    u64_idx: usize,
    u64_val: u64,
    num_garbage_bits_in_last_u64: u8,
}

impl<'a> OnesIter<'a> {
    fn new(bits: &'a AtomicBits) -> Self {
        let num_garbage_bits_in_last_u64 = {
            if bits.len() % 64 != 0 {
                64 - ((bits.len() % 64) as u8)
            } else {
                0
            }
        };
        let mut new_self = Self {
            bits,
            u64_idx: 0,
            u64_val: 0, // NOT initalized yet!
            num_garbage_bits_in_last_u64,
        };
        new_self.u64_val = new_self.get_u64_val(0);
        new_self
    }

    /// Gets the u64 value at the given position, removing the garbage bits if any.
    fn get_u64_val(&self, idx: usize) -> u64 {
        let mut u64_val = self.bits.u64s[idx].load(Relaxed);
        // Clear the garbage bits, if any, in the last u64 so that they
        // won't affect the result of the iterator.
        if idx == self.bits.u64s.len() - 1 && self.num_garbage_bits_in_last_u64 > 0 {
            let num_valid_bits_in_last_u64 = 64 - self.num_garbage_bits_in_last_u64;
            let valid_bits_mask = (1 << num_valid_bits_in_last_u64) - 1;
            u64_val &= valid_bits_mask;
        }
        u64_val
    }
}

impl<'a> Iterator for OnesIter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        loop {
            if self.u64_idx >= self.bits.u64s.len() {
                return None;
            }

            let first_one_in_u64 = self.u64_val.trailing_zeros() as usize;
            if first_one_in_u64 < 64 {
                self.u64_val &= !(1 << first_one_in_u64);
                let one_pos = self.u64_idx * 64 + first_one_in_u64;
                return Some(one_pos);
            }

            self.u64_idx += 1;
            if self.u64_idx < self.bits.u64s.len() {
                self.u64_val = self.get_u64_val(self.u64_idx);
            }
        }
    }
}

/// An iterator that returns the positions of 0s in an [`AtomicBits`].
pub struct ZeroesIter<'a> {
    bits: &'a AtomicBits,
    u64_idx: usize,
    u64_val: u64,
    num_garbage_bits_in_last_u64: u8,
}

impl<'a> ZeroesIter<'a> {
    fn new(bits: &'a AtomicBits) -> Self {
        let num_garbage_bits_in_last_u64 = {
            if bits.len() % 64 != 0 {
                64 - ((bits.len() % 64) as u8)
            } else {
                0
            }
        };
        let mut new_self = Self {
            bits,
            u64_idx: 0,
            u64_val: 0, // NOT initalized yet!
            num_garbage_bits_in_last_u64,
        };
        new_self.u64_val = new_self.get_u64_val(0);
        new_self
    }

    /// Gets the u64 value at the given position, removing the garbage bits if any.
    fn get_u64_val(&self, idx: usize) -> u64 {
        let mut u64_val = self.bits.u64s[idx].load(Relaxed);
        // Set all garbage bits, if any, in the last u64 so that they
        // won't affect the result of the iterator.
        if idx == self.bits.u64s.len() - 1 && self.num_garbage_bits_in_last_u64 > 0 {
            let num_valid_bits_in_last_u64 = 64 - self.num_garbage_bits_in_last_u64;
            let garbage_bits_mask = !((1 << num_valid_bits_in_last_u64) - 1);
            u64_val |= garbage_bits_mask;
        }
        u64_val
    }
}

impl<'a> Iterator for ZeroesIter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        loop {
            if self.u64_idx >= self.bits.u64s.len() {
                return None;
            }

            let first_zero_in_u64 = self.u64_val.trailing_ones() as usize;
            if first_zero_in_u64 < 64 {
                self.u64_val |= 1 << first_zero_in_u64;
                let one_pos = self.u64_idx * 64 + first_zero_in_u64;
                return Some(one_pos);
            }

            self.u64_idx += 1;
            if self.u64_idx < self.bits.u64s.len() {
                self.u64_val = self.get_u64_val(self.u64_idx);
            }
        }
    }
}

impl Clone for AtomicBits {
    fn clone(&self) -> Self {
        let num_bits = self.num_bits;
        let num_u64s = self.u64s.len();
        let u64s = {
            let mut u64s = Vec::with_capacity(num_u64s);
            for u64_i in 0..num_u64s {
                let u64_val = self.u64s[u64_i].load(Relaxed);
                u64s.push(AtomicU64::new(u64_val));
            }
            u64s.into_boxed_slice()
        };
        Self { num_bits, u64s }
    }
}

impl fmt::Debug for AtomicBits {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "AtomicBits(")?;
        for bit in self.iter() {
            if bit {
                write!(f, "1")?;
            } else {
                write!(f, "0")?;
            }
        }
        write!(f, ")")
    }
}

#[cfg(ktest)]
mod test {
    use super::*;
    use crate::prelude::*;

    #[ktest]
    fn new() {
        let bits = AtomicBits::new_zeroes(1);
        assert!(bits.len() == 1);

        let bits = AtomicBits::new_zeroes(128);
        assert!(bits.len() == 128);

        let bits = AtomicBits::new_ones(7);
        assert!(bits.len() == 7);

        let bits = AtomicBits::new_zeroes(65);
        assert!(bits.len() == 65);
    }

    #[ktest]
    fn set_get() {
        let bits = AtomicBits::new_zeroes(128);
        for i in 0..bits.len() {
            assert!(bits.get(i) == false);

            bits.set(i, true);
            assert!(bits.get(i) == true);

            bits.set(i, false);
            assert!(bits.get(i) == false);
        }

        let bits = AtomicBits::new_ones(128);
        for i in 0..bits.len() {
            assert!(bits.get(i) == true);

            bits.set(i, false);
            assert!(bits.get(i) == false);

            bits.set(i, true);
            assert!(bits.get(i) == true);
        }
    }

    #[ktest]
    fn iter_ones() {
        let bits = AtomicBits::new_zeroes(1);
        assert!(bits.iter_ones().count() == 0);
        let bits = AtomicBits::new_zeroes(400);
        assert!(bits.iter_ones().count() == 0);

        let bits = AtomicBits::new_ones(1);
        assert!(bits.iter_ones().count() == 1);
        let bits = AtomicBits::new_ones(24);
        assert!(bits.iter_ones().count() == 24);
        let bits = AtomicBits::new_ones(64);
        assert!(bits.iter_ones().count() == 64);
        let bits = AtomicBits::new_ones(77);
        assert!(bits.iter_ones().count() == 77);
        let bits = AtomicBits::new_ones(128);
        assert!(bits.iter_ones().count() == 128);

        let bits = AtomicBits::new_zeroes(8);
        bits.set(1, true);
        bits.set(3, true);
        bits.set(5, true);
        assert!(bits.iter_ones().count() == 3);
    }

    #[ktest]
    fn iter_zeroes() {
        let bits = AtomicBits::new_ones(1);
        assert!(bits.iter_zeroes().count() == 0);
        let bits = AtomicBits::new_ones(130);
        assert!(bits.iter_zeroes().count() == 0);

        let bits = AtomicBits::new_zeroes(1);
        assert!(bits.iter_zeroes().count() == 1);
        let bits = AtomicBits::new_zeroes(24);
        assert!(bits.iter_zeroes().count() == 24);
        let bits = AtomicBits::new_zeroes(64);
        assert!(bits.iter_zeroes().count() == 64);
        let bits = AtomicBits::new_zeroes(77);
        assert!(bits.iter_zeroes().count() == 77);
        let bits = AtomicBits::new_zeroes(128);
        assert!(bits.iter_zeroes().count() == 128);

        let bits = AtomicBits::new_ones(96);
        bits.set(1, false);
        bits.set(3, false);
        bits.set(5, false);
        bits.set(64, false);
        bits.set(76, false);
        assert!(bits.iter_zeroes().count() == 5);
    }

    #[ktest]
    fn iter() {
        let bits = AtomicBits::new_zeroes(7);
        assert!(bits.iter().all(|bit| bit == false));

        let bits = AtomicBits::new_ones(128);
        assert!(bits.iter().all(|bit| bit == true));
    }
}