Factor out LockedPubkeyReferences (#10198)

Co-authored-by: Carl <carl@solana.com>
This commit is contained in:
carllin
2020-05-22 23:23:17 -07:00
committed by GitHub
parent 36a36d1c83
commit 42aaacf520
3 changed files with 39 additions and 32 deletions

View File

@@ -1,5 +1,9 @@
use solana_sdk::pubkey::Pubkey;
use std::{collections::HashSet, rc::Rc};
use std::{
collections::HashSet,
rc::Rc,
sync::{Arc, RwLock},
};
#[derive(Default)]
pub struct PubkeyReferences(HashSet<Rc<Pubkey>>);
@@ -19,3 +23,22 @@ impl PubkeyReferences {
self.0.retain(|x| Rc::strong_count(x) > 1);
}
}
#[derive(Default)]
pub struct LockedPubkeyReferences(pub RwLock<HashSet<Arc<Pubkey>>>);
impl LockedPubkeyReferences {
pub fn get_or_insert(&self, pubkey: &Pubkey) -> Arc<Pubkey> {
let mut cached_pubkey = self.0.read().unwrap().get(pubkey).cloned();
if cached_pubkey.is_none() {
let new_pubkey = Arc::new(*pubkey);
self.0.write().unwrap().insert(new_pubkey.clone());
cached_pubkey = Some(new_pubkey);
}
cached_pubkey.unwrap()
}
pub fn purge(&self) {
self.0.write().unwrap().retain(|x| Arc::strong_count(x) > 1);
}
}