Skip to content

Instantly share code, notes, and snippets.

@twe4ked
Created November 18, 2020 22:09
Show Gist options
  • Save twe4ked/e537922d271f4b0226ec3aec4b689acf to your computer and use it in GitHub Desktop.
Save twe4ked/e537922d271f4b0226ec3aec4b689acf to your computer and use it in GitHub Desktop.
use std::collections::HashSet;
use std::sync::{Arc, RwLock, RwLockReadGuard};
/// A HashSet that allows controlling when items are actually removed from the list.
/// This can be helpful if you need to keep track of items being added over time
/// and ensuring that they don't get added _and_ removed before you've read them.
struct LockedHashSet {
values: Arc<RwLock<HashSet<u64>>>,
values_marked_for_removal: Arc<RwLock<HashSet<u64>>>,
}
impl LockedHashSet {
fn add(&self, value: u64) {
self.values.write().unwrap().insert(value);
}
fn read(&self) -> RwLockReadGuard<HashSet<u64>> {
self.values.read().unwrap()
}
fn mark_for_removal(&self, value: u64) {
self.values_marked_for_removal
.write()
.unwrap()
.insert(value);
}
fn remove_marked_for_removal(&self) {
let mut values = self.values.write().unwrap();
for sequence in self.values_marked_for_removal.write().unwrap().drain() {
values.remove(&sequence);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment