Skip to content

Commit

Permalink
AtomicBitset::swap method
Browse files Browse the repository at this point in the history
  • Loading branch information
micahrj committed Sep 2, 2024
1 parent fe2071b commit b64d031
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/sync/bitset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,21 @@ impl AtomicBitset {
}
}

#[inline]
pub fn swap(&self, index: usize, value: bool, ordering: Ordering) -> bool {
assert!(index < self.len);

let mask = 1 << (index & WORD_SIZE_MASK);
let word = &self.words[index >> WORD_SIZE_SHIFT];
let word_prev = if value {
word.fetch_or(mask, ordering)
} else {
word.fetch_and(!mask, ordering)
};

word_prev & mask != 0
}

#[inline]
pub fn get(&self, index: usize, ordering: Ordering) -> bool {
assert!(index < self.len);
Expand Down Expand Up @@ -163,6 +178,19 @@ mod tests {
}
}

#[test]
fn atomic_swap() {
let bitset = AtomicBitset::with_len(8);

for index in 0..8 {
let prev = bitset.swap(index, true, Ordering::Relaxed);
assert!(!prev);

let prev = bitset.swap(index, false, Ordering::Relaxed);
assert!(prev);
}
}

#[test]
fn atomic_drain() {
let bitset = AtomicBitset::with_len(8);
Expand Down

0 comments on commit b64d031

Please sign in to comment.