bitflagset 0.0.3

Enum and positional typed bitsets with Set API
Documentation
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::ops::BitAndAssign;
use core::sync::atomic::Ordering;
use num_traits::{One, PrimInt, Zero};
use radium::Radium;

use super::bitset::PrimBitSetIter;

/// Unsized shared base for multi-word atomic bitset types.
///
/// `AtomicBitSlice<A, V>` is to atomic bitsets what [`BitSlice<T, V>`](super::BitSlice)
/// is to non-atomic ones: a `#[repr(transparent)]` wrapper around `[A]` that provides
/// common query and mutation methods. Owned types ([`AtomicBitSet<[A; N], V>`](super::AtomicBitSet)
/// and [`AtomicBoxedBitSet<A, V>`](super::AtomicBoxedBitSet)) implement
/// `Deref<Target = AtomicBitSlice<A, V>>`.
///
/// # Atomicity guarantees
///
/// Each individual method (`insert`, `remove`, `contains`, ...) performs atomic
/// operations **per word**. However, the bitset as a whole is **not** a single
/// atomic unit when it spans multiple words. Concurrent modifications to bits
/// within the **same word** are correctly synchronized via `fetch_or` / `fetch_and`
/// with `AcqRel` ordering. Modifications to bits in **different words** are
/// independent atomic operations — there is no cross-word transactional guarantee.
///
/// Read-only methods (`len`, `iter`, `contains`, `is_subset`, …) load each word
/// with `Relaxed` ordering and do not take a consistent snapshot of the entire
/// bitset. If another thread modifies the set concurrently, these methods may
/// observe a mix of old and new state across different words.
#[repr(transparent)]
pub struct AtomicBitSlice<A, V>(PhantomData<V>, [A]);

impl<A, V> AtomicBitSlice<A, V> {
    pub(crate) fn from_slice_ref(s: &[A]) -> &Self {
        // SAFETY: AtomicBitSlice<A, V> is repr(transparent) over [A]
        // (PhantomData<V> is ZST)
        unsafe { &*(s as *const [A] as *const Self) }
    }

    #[inline]
    pub fn as_raw_slice(&self) -> &[A] {
        &self.1
    }
}

impl<A, V> AtomicBitSlice<A, V>
where
    A: Radium,
    A::Item: PrimInt,
{
    const BITS_PER: usize = core::mem::size_of::<A>() * 8;

    #[inline]
    fn index_of(idx: usize) -> (usize, A::Item) {
        (
            idx / Self::BITS_PER,
            <A::Item as num_traits::One>::one().unsigned_shl((idx % Self::BITS_PER) as u32),
        )
    }

    #[inline]
    pub fn capacity(&self) -> usize {
        self.1.len() * Self::BITS_PER
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.1
            .iter()
            .map(|a| a.load(Ordering::Relaxed).count_ones() as usize)
            .sum()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.1.iter().all(|a| a.load(Ordering::Relaxed).is_zero())
    }

    #[inline]
    pub fn first(&self) -> Option<V>
    where
        V: TryFrom<usize>,
    {
        for (i, a) in self.1.iter().enumerate() {
            let word = a.load(Ordering::Relaxed);
            if !word.is_zero() {
                let bit = word.trailing_zeros() as usize;
                return V::try_from(i * Self::BITS_PER + bit).ok();
            }
        }
        None
    }

    #[inline]
    pub fn last(&self) -> Option<V>
    where
        V: TryFrom<usize>,
    {
        for (i, a) in self.1.iter().enumerate().rev() {
            let word = a.load(Ordering::Relaxed);
            if !word.is_zero() {
                let bit = Self::BITS_PER - 1 - word.leading_zeros() as usize;
                return V::try_from(i * Self::BITS_PER + bit).ok();
            }
        }
        None
    }

    #[inline]
    pub fn pop_first(&self) -> Option<V>
    where
        V: TryFrom<usize>,
        A::Item: radium::marker::BitOps,
    {
        for (i, a) in self.1.iter().enumerate() {
            loop {
                let word = a.load(Ordering::Acquire);
                if word.is_zero() {
                    break;
                }
                let bit = word.trailing_zeros() as usize;
                let mask = A::Item::one().unsigned_shl(bit as u32);
                let old = a.fetch_and(!mask, Ordering::AcqRel);
                if old & mask != A::Item::zero() {
                    return V::try_from(i * Self::BITS_PER + bit).ok();
                }
            }
        }
        None
    }

    #[inline]
    pub fn pop_last(&self) -> Option<V>
    where
        V: TryFrom<usize>,
        A::Item: radium::marker::BitOps,
    {
        for (i, a) in self.1.iter().enumerate().rev() {
            loop {
                let word = a.load(Ordering::Acquire);
                if word.is_zero() {
                    break;
                }
                let bit = Self::BITS_PER - 1 - word.leading_zeros() as usize;
                let mask = A::Item::one().unsigned_shl(bit as u32);
                let old = a.fetch_and(!mask, Ordering::AcqRel);
                if old & mask != A::Item::zero() {
                    return V::try_from(i * Self::BITS_PER + bit).ok();
                }
            }
        }
        None
    }

    #[inline]
    pub fn contains(&self, id: &V) -> bool
    where
        V: Copy + num_traits::AsPrimitive<usize>,
    {
        let idx = (*id).as_();
        let (seg, mask) = Self::index_of(idx);
        if seg >= self.1.len() {
            return false;
        }
        // SAFETY: seg < self.1.len() checked above.
        let a = unsafe { self.1.get_unchecked(seg) };
        a.load(Ordering::Relaxed) & mask != A::Item::zero()
    }

    #[inline]
    pub fn insert(&self, id: V) -> bool
    where
        V: num_traits::AsPrimitive<usize>,
        A::Item: radium::marker::BitOps,
    {
        let idx = id.as_();
        let (seg, mask) = Self::index_of(idx);
        if seg >= self.1.len() {
            return false;
        }
        // SAFETY: seg < self.1.len() checked above.
        let a = unsafe { self.1.get_unchecked(seg) };
        let old = a.fetch_or(mask, Ordering::AcqRel);
        old & mask == A::Item::zero()
    }

    #[inline]
    pub fn remove(&self, id: V) -> bool
    where
        V: num_traits::AsPrimitive<usize>,
        A::Item: radium::marker::BitOps,
    {
        let idx = id.as_();
        let (seg, mask) = Self::index_of(idx);
        if seg >= self.1.len() {
            return false;
        }
        // SAFETY: seg < self.1.len() checked above.
        let a = unsafe { self.1.get_unchecked(seg) };
        let old = a.fetch_and(!mask, Ordering::AcqRel);
        old & mask != A::Item::zero()
    }

    #[inline]
    pub fn set(&self, id: V, value: bool)
    where
        V: num_traits::AsPrimitive<usize>,
        A::Item: radium::marker::BitOps,
    {
        if value {
            self.insert(id);
        } else {
            self.remove(id);
        }
    }

    #[inline]
    pub fn toggle(&self, id: V)
    where
        V: num_traits::AsPrimitive<usize>,
        A::Item: radium::marker::BitOps,
    {
        let idx = id.as_();
        let (seg, mask) = Self::index_of(idx);
        if seg >= self.1.len() {
            return;
        }
        // SAFETY: seg < self.1.len() checked above.
        let a = unsafe { self.1.get_unchecked(seg) };
        a.fetch_xor(mask, Ordering::AcqRel);
    }

    #[inline]
    pub fn clear(&self) {
        for atomic in self.1.iter() {
            atomic.store(A::Item::zero(), Ordering::Release);
        }
    }

    pub fn retain(&self, mut f: impl FnMut(V) -> bool)
    where
        V: TryFrom<usize>,
        A::Item: radium::marker::BitOps,
    {
        for (i, a) in self.1.iter().enumerate() {
            let word = a.load(Ordering::Relaxed);
            let mut w = word;
            while !w.is_zero() {
                let bit = w.trailing_zeros() as usize;
                let mask = A::Item::one().unsigned_shl(bit as u32);
                w = w & !mask;
                let idx = i * Self::BITS_PER + bit;
                debug_assert!(V::try_from(idx).is_ok());
                let value = match V::try_from(idx) {
                    Ok(v) => v,
                    Err(_) => unsafe { core::hint::unreachable_unchecked() },
                };
                if !f(value) {
                    a.fetch_and(!mask, Ordering::AcqRel);
                }
            }
        }
    }

    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = V> + '_
    where
        A::Item: BitAndAssign,
        V: TryFrom<usize>,
    {
        self.1.iter().enumerate().flat_map(move |(i, a)| {
            let bits = a.load(Ordering::Relaxed);
            let offset = i * Self::BITS_PER;
            PrimBitSetIter::<A::Item, usize>(bits, PhantomData).map(move |pos| {
                let idx = offset + pos;
                debug_assert!(V::try_from(idx).is_ok());
                match V::try_from(idx) {
                    Ok(v) => v,
                    Err(_) => unsafe { core::hint::unreachable_unchecked() },
                }
            })
        })
    }

    #[inline]
    pub fn is_subset(&self, other: &Self) -> bool {
        let min = self.1.len().min(other.1.len());
        self.1[..min]
            .iter()
            .zip(other.1[..min].iter())
            .all(|(a, b)| {
                let va = a.load(Ordering::Relaxed);
                let vb = b.load(Ordering::Relaxed);
                va & vb == va
            })
            && self.1[min..]
                .iter()
                .all(|a| a.load(Ordering::Relaxed).is_zero())
    }

    #[inline]
    pub fn is_superset(&self, other: &Self) -> bool {
        other.is_subset(self)
    }

    #[inline]
    pub fn is_disjoint(&self, other: &Self) -> bool {
        self.1.iter().zip(other.1.iter()).all(|(a, b)| {
            let va = a.load(Ordering::Relaxed);
            let vb = b.load(Ordering::Relaxed);
            (va & vb).is_zero()
        })
    }

    fn word_op_iter<'a>(
        a: &'a [A],
        b: &'a [A],
        len: usize,
        op: impl Fn(A::Item, A::Item) -> A::Item + 'a,
    ) -> impl Iterator<Item = V> + 'a
    where
        A::Item: BitAndAssign,
        V: TryFrom<usize>,
    {
        let bits_per = Self::BITS_PER;
        (0..len).flat_map(move |i| {
            let w_a = a
                .get(i)
                .map(|a| a.load(Ordering::Relaxed))
                .unwrap_or(A::Item::zero());
            let w_b = b
                .get(i)
                .map(|a| a.load(Ordering::Relaxed))
                .unwrap_or(A::Item::zero());
            let combined = op(w_a, w_b);
            let offset = i * bits_per;
            PrimBitSetIter::<A::Item, usize>(combined, PhantomData).map(move |pos| {
                let idx = offset + pos;
                debug_assert!(V::try_from(idx).is_ok());
                match V::try_from(idx) {
                    Ok(v) => v,
                    Err(_) => unsafe { core::hint::unreachable_unchecked() },
                }
            })
        })
    }

    #[inline]
    pub fn difference<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = V> + 'a
    where
        A::Item: BitAndAssign,
        V: TryFrom<usize>,
    {
        Self::word_op_iter(&self.1, &other.1, self.1.len(), |a, b| a & !b)
    }

    #[inline]
    pub fn intersection<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = V> + 'a
    where
        A::Item: BitAndAssign,
        V: TryFrom<usize>,
    {
        Self::word_op_iter(
            &self.1,
            &other.1,
            self.1.len().min(other.1.len()),
            |a, b| a & b,
        )
    }

    #[inline]
    pub fn union<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = V> + 'a
    where
        A::Item: BitAndAssign,
        V: TryFrom<usize>,
    {
        Self::word_op_iter(
            &self.1,
            &other.1,
            self.1.len().max(other.1.len()),
            |a, b| a | b,
        )
    }

    #[inline]
    pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = V> + 'a
    where
        A::Item: BitAndAssign,
        V: TryFrom<usize>,
    {
        Self::word_op_iter(
            &self.1,
            &other.1,
            self.1.len().max(other.1.len()),
            |a, b| a ^ b,
        )
    }

    pub fn append(&self, other: &Self)
    where
        A::Item: radium::marker::BitOps + Copy,
    {
        let min = self.1.len().min(other.1.len());
        for i in 0..min {
            let val = other.1[i].swap(A::Item::zero(), Ordering::AcqRel);
            self.1[i].fetch_or(val, Ordering::AcqRel);
        }
        // Clear remaining words in other beyond self's range
        for a in &other.1[min..] {
            a.store(A::Item::zero(), Ordering::Release);
        }
    }

    #[inline]
    pub fn union_from(&self, other: &[A::Item])
    where
        A::Item: radium::marker::BitOps + Copy,
    {
        for (atomic, &value) in self.1.iter().zip(other.iter()) {
            atomic.fetch_or(value, Ordering::AcqRel);
        }
    }
}

impl<A, V> Hash for AtomicBitSlice<A, V>
where
    A: Radium,
    A::Item: Hash + PrimInt,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        let effective_len = self
            .1
            .iter()
            .rposition(|a| !a.load(Ordering::Relaxed).is_zero())
            .map_or(0, |i| i + 1);
        for a in &self.1[..effective_len] {
            a.load(Ordering::Relaxed).hash(state);
        }
    }
}

impl<A, V> core::fmt::Debug for AtomicBitSlice<A, V>
where
    A: Radium,
    A::Item: PrimInt + BitAndAssign,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let bits_per = core::mem::size_of::<A>() * 8;
        f.write_str("{")?;
        let mut first = true;
        for (i, a) in self.1.iter().enumerate() {
            let word = a.load(Ordering::Relaxed);
            let offset = i * bits_per;
            for pos in PrimBitSetIter::<A::Item, usize>(word, PhantomData) {
                if !first {
                    f.write_str(", ")?;
                }
                first = false;
                write!(f, "{}", offset + pos)?;
            }
        }
        f.write_str("}")
    }
}

impl<A, V> core::fmt::Display for AtomicBitSlice<A, V>
where
    A: Radium,
    A::Item: PrimInt + BitAndAssign,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(self, f)
    }
}