Skip to content

Instantly share code, notes, and snippets.

@t-sin
Created June 18, 2019 18:36
Show Gist options
  • Save t-sin/743f70f580844f257b9a7de4a665f698 to your computer and use it in GitHub Desktop.
Save t-sin/743f70f580844f257b9a7de4a665f698 to your computer and use it in GitHub Desktop.
How to implement HashMap-insertable Mutex
use std::cmp::{PartialEq, Eq};
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
#[derive(Debug, Hash)]
struct Hoge {
a: u32,
b: u32,
}
#[derive(Debug)]
struct MutHoge(Mutex<Hoge>);
impl Hash for MutHoge {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.lock().unwrap().hash(state)
}
}
impl PartialEq for MutHoge {
fn eq(&self, other: &Self) -> bool {
let s = self.0.lock().unwrap();
let o = other.0.lock().unwrap();
s.a == o.a && s.b == o.b
}
}
impl Eq for MutHoge {}
fn main() {
let h1 = Arc::new(MutHoge(Mutex::new(Hoge {a:1,b:2})));
let mut map = HashMap::new();
map.insert(h1.clone(), "hoge");
map.insert(h1, "hoge");
println!("{:?}", map);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment