use std::collections::HashSet;
use std::sync::{Arc, RwLock};
#[derive(Clone, Debug, Default)]
pub struct ActiveSkillSet {
names: Arc<RwLock<HashSet<String>>>,
}
impl ActiveSkillSet {
pub fn new() -> Self {
Self::default()
}
pub fn mark_active(&self, name: impl Into<String>) {
self.names.write().unwrap().insert(name.into());
}
pub fn is_active(&self, name: &str) -> bool {
self.names.read().unwrap().contains(name)
}
pub fn replace(&self, names: impl IntoIterator<Item = String>) {
let mut guard = self.names.write().unwrap();
guard.clear();
guard.extend(names);
}
pub fn names(&self) -> Vec<String> {
let mut v: Vec<String> = self.names.read().unwrap().iter().cloned().collect();
v.sort();
v
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mark_query_replace_are_shared_across_clones() {
let set = ActiveSkillSet::default();
let handle = set.clone();
assert!(!set.is_active("review"));
handle.mark_active("review");
assert!(set.is_active("review"), "clone writes are visible to all");
assert_eq!(set.names(), vec!["review".to_string()]);
set.replace(["ship".to_string()]);
assert!(!set.is_active("review"), "replace drops stale names");
assert!(handle.is_active("ship"));
}
}