commit | ef8197124a81832b51ce480e5fbcf74dff836e4f | [log] [tgz] |
---|---|---|
author | Bob Badour <bbadour@google.com> | Tue Feb 16 21:22:24 2021 +0000 |
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | Tue Feb 16 21:22:24 2021 +0000 |
tree | f32d89028ab9efbc8f60d4a24af0f7f26f270740 | |
parent | 2f984ae8fef523da9e4afe1e2bf49c388ebbad06 [diff] | |
parent | b5ceed2b176d4c6c8445a8e982fcd97ae8246412 [diff] |
[LSC] Add LOCAL_LICENSE_KINDS to external/rust/crates/weak-table am: 52db6ac03e am: b5ceed2b17 Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/weak-table/+/1588756 MUST ONLY BE SUBMITTED BY AUTOMERGER Change-Id: Iebc88499331466781b6aa031132c1ea07ddb1504
This crate defines several kinds of weak hash maps and sets. See the full API documentation for details.
This crate supports Rust version 1.32 and later.
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); }