Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 18, 2018 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/c88a828b9ef87b3bd6a4b6b9e9fda7f9 to your computer and use it in GitHub Desktop.
Save rust-play/c88a828b9ef87b3bd6a4b6b9e9fda7f9 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Default)]
struct StringManagerPrimative {
pub map: HashMap<String, String>,
}
impl StringManagerPrimative {
fn ref_string(&mut self, stuff: String) {
self.map.insert(stuff.clone(), stuff);
}
fn unref(&mut self, stuff: &str) {
self.map.remove(stuff);
}
}
#[derive(Default)]
struct StringManager {
primative: Arc<Mutex<StringManagerPrimative>>,
}
impl StringManager {
fn get(&mut self, head: &str) -> It
{
self.primative.lock().unwrap().ref_string(head.into());
let unref_head = head.clone().to_string();
let unref_primative = self.primative.clone();
It::new(head,
Box::new(
move || {
println!("dropping ref to \"{}\"", unref_head);
unref_primative.lock().unwrap().unref(&unref_head);
}))
}
fn new() -> Self {
StringManager::default()
}
}
struct It {
s: String,
on_drop: Box<Fn() -> ()>
}
impl It {
fn new(s: &str, on_drop: Box<Fn() -> ()>) -> Self {
It {
s: s.into(),
on_drop,
}
}
}
impl Drop for It {
fn drop(&mut self) {
(*self.on_drop)();
}
}
fn main() {
let mut string_manager = StringManager::new();
let it = string_manager.get("hello");
println!("It: {}", it.s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment