From 3b6c19401cb74a0f4ac2128f3d335377370b14cf Mon Sep 17 00:00:00 2001 From: Dorota Czaplejewicz Date: Thu, 17 Oct 2019 13:59:01 +0000 Subject: [PATCH] util: Added pointer comparison struct util::Pointer should be suitable for storing key states in bags like pressed_keys --- src/util.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/util.rs b/src/util.rs index 935250b9..350326f7 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,6 +1,8 @@ /*! Assorted helpers */ use std::collections::HashMap; +use std::rc::Rc; +use std::hash::{ Hash, Hasher }; use std::iter::FromIterator; pub mod c { @@ -129,3 +131,36 @@ pub fn hash_map_map(map: HashMap, mut f: F) map.into_iter().map(|(key, value)| f(key, value)) ) } + +/// Compares pointers but not internal values of Rc +pub struct Pointer(Rc); + +impl Hash for Pointer { + fn hash(&self, state: &mut H) { + (&*self.0 as *const T).hash(state); + } +} + +impl PartialEq for Pointer { + fn eq(&self, other: &Pointer) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for Pointer {} + +#[cfg(test)] +mod tests { + use super::*; + + use std::collections::HashSet; + + #[test] + fn check_set() { + let mut s = HashSet::new(); + let first = Rc::new(1u32); + s.insert(Pointer(first.clone())); + assert_eq!(s.insert(Pointer(Rc::new(2u32))), true); + assert_eq!(s.remove(&Pointer(first)), true); + } +}