tag | a4691a9e029150fe5e6ef416634ace58ef36a93c | |
---|---|---|
tagger | The Android Open Source Project <initial-contribution@android.com> | Wed Apr 24 20:07:44 2024 -0700 |
object | efb77a2d9450720c7e24f11889f5173224b3dff9 |
aml_sta_341615000 (11423312,com.google.android.go.os.statsd,com.google.android.os.statsd)
commit | efb77a2d9450720c7e24f11889f5173224b3dff9 | [log] [tgz] |
---|---|---|
author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | Fri Jul 07 05:07:40 2023 +0000 |
committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | Fri Jul 07 05:07:40 2023 +0000 |
tree | b9732a1c26db90ebe03598eddae2c757483d6044 | |
parent | 7975499b7b3b04cb6578445b466a215bdbe6114b [diff] | |
parent | 84cc89dbdd177a1d193defb64a1f03ef9bf44e87 [diff] |
Snap for 10453563 from 84cc89dbdd177a1d193defb64a1f03ef9bf44e87 to mainline-os-statsd-release Change-Id: Ib0739d6c00620078bdd6e5c2f89ecfed9c3b73c5
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); }