-
-
Save peterschwarz/12078eb07df466ec091fbb09c1373d11 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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