Implement Hash for Dynamic.

This commit is contained in:
Stephen Chung 2020-11-12 21:53:26 +08:00
parent 41c815f355
commit 8e5a53bc0d
2 changed files with 35 additions and 0 deletions

View File

@ -836,6 +836,7 @@ pub struct FloatWrapper(pub FLOAT);
impl Hash for FloatWrapper {
#[inline(always)]
fn hash<H: Hasher>(&self, state: &mut H) {
TypeId::of::<FLOAT>().hash(state);
state.write(&self.0.to_le_bytes());
}
}

View File

@ -21,6 +21,7 @@ use crate::stdlib::{
any::{type_name, Any, TypeId},
boxed::Box,
fmt,
hash::{Hash, Hasher},
ops::{Deref, DerefMut},
string::{String, ToString},
};
@ -361,6 +362,39 @@ impl Dynamic {
}
}
impl Hash for Dynamic {
fn hash<H: Hasher>(&self, state: &mut H) {
match &self.0 {
Union::Unit(_) => ().hash(state),
Union::Bool(value) => value.hash(state),
Union::Str(s) => s.hash(state),
Union::Char(ch) => ch.hash(state),
Union::Int(i) => i.hash(state),
#[cfg(not(feature = "no_float"))]
Union::Float(f) => {
TypeId::of::<FLOAT>().hash(state);
state.write(&f.to_le_bytes());
}
#[cfg(not(feature = "no_index"))]
Union::Array(a) => a.hash(state),
#[cfg(not(feature = "no_object"))]
Union::Map(m) => m.iter().for_each(|(key, item)| {
key.hash(state);
item.hash(state);
}),
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))]
Union::Shared(cell) => (*cell.borrow()).hash(state),
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
Union::Shared(cell) => (*cell.read().unwrap()).hash(hasher),
_ => unimplemented!(),
}
}
}
/// Map the name of a standard type into a friendly form.
#[inline]
pub(crate) fn map_std_type_name(name: &str) -> &str {