tag | 8ae60a828dd0a7f47ad53f02554912cab9821bb1 | |
---|---|---|
tagger | The Android Open Source Project <initial-contribution@android.com> | Mon Apr 24 16:01:46 2023 -0700 |
object | 140e95a0d698c512e8f28c5961d2a2c6bd38363f |
aml_ads_331611190 (9773358,com.google.android.adservices)
commit | 140e95a0d698c512e8f28c5961d2a2c6bd38363f | [log] [tgz] |
---|---|---|
author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | Wed Mar 16 22:42:33 2022 +0000 |
committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | Wed Mar 16 22:42:33 2022 +0000 |
tree | 93f36fb91d268cdae444791dbbdcc6bd50de9034 | |
parent | 0386b920206ee7081d86adcedbd1262fb6bc511a [diff] | |
parent | 3dc30e23e1f24a7cf8862f6fed1166a68ddca94d [diff] |
Snap for 8310876 from 3dc30e23e1f24a7cf8862f6fed1166a68ddca94d to mainline-adservices-release Change-Id: I0d4a506e4ec1c257ddb43a97b713d83b7112466a
This crate defines several kinds of weak hash maps and sets. See the full API documentation for details.
This crate supports Rust version 1.46 and later.
weak-table
is built with the std
feature, which enables functionality dependent on the std
library, enabled by default. Optionally, the following dependency may be enabled:
ahash
: use ahash
’s hasher rather than the std
hasherIf the std
feature is disabled (for no_std) then the ahash
dependency must be enabled.
Here we create a weak hash map and demonstrate that it forgets mappings whose keys expire:
use weak_table::WeakKeyHashMap; use std::sync::{Arc, Weak}; let mut table = <WeakKeyHashMap<Weak<str>, u32>>::new(); let one = Arc::<str>::from("one"); let two = Arc::<str>::from("two"); table.insert(one.clone(), 1); assert_eq!( table.get("one"), Some(&1) ); assert_eq!( table.get("two"), None ); table.insert(two.clone(), 2); *table.get_mut(&one).unwrap() += 10; assert_eq!( table.get("one"), Some(&11) ); assert_eq!( table.get("two"), Some(&2) ); drop(one); assert_eq!( table.get("one"), None ); assert_eq!( table.get("two"), Some(&2) );
Here we use a weak hash set to implement a simple string interning facility:
use weak_table::WeakHashSet; use std::ops::Deref; use std::rc::{Rc, Weak}; #[derive(Clone, Debug)] pub struct Symbol(Rc<str>); impl PartialEq for Symbol { fn eq(&self, other: &Symbol) -> bool { Rc::ptr_eq(&self.0, &other.0) } } impl Eq for Symbol {} impl Deref for Symbol { type Target = str; fn deref(&self) -> &str { &self.0 } } #[derive(Debug, Default)] pub struct SymbolTable(WeakHashSet<Weak<str>>); impl SymbolTable { pub fn new() -> Self { Self::default() } pub fn intern(&mut self, name: &str) -> Symbol { if let Some(rc) = self.0.get(name) { Symbol(rc) } else { let rc = Rc::<str>::from(name); self.0.insert(Rc::clone(&rc)); Symbol(rc) } } } #[test] fn interning() { let mut tab = SymbolTable::new(); let a0 = tab.intern("a"); let a1 = tab.intern("a"); let b = tab.intern("b"); assert_eq!(a0, a1); assert_ne!(a0, b); }