10 releases

0.3.0 Jun 27, 2020
0.2.4 Jun 27, 2020
0.2.3 May 30, 2018
0.1.3 May 22, 2018
0.1.1 Mar 5, 2018

#8 in Memory management

Download history 1535/week @ 2020-07-05 2543/week @ 2020-07-12 1766/week @ 2020-07-19 2567/week @ 2020-07-26 1931/week @ 2020-08-02 1425/week @ 2020-08-09 1180/week @ 2020-08-16 1337/week @ 2020-08-23 2567/week @ 2020-08-30 2432/week @ 2020-09-06 2272/week @ 2020-09-13 1818/week @ 2020-09-20 4452/week @ 2020-09-27 4955/week @ 2020-10-04 4315/week @ 2020-10-11 3350/week @ 2020-10-18

8,303 downloads per month
Used in 24 crates (6 directly)

MIT license

135KB
3K SLoC

weak-table: weak hash maps and sets for Rust

Build Status Crates.io License: MIT

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.

Examples

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);
}

No runtime deps