From e089b6ea40015e012302dc55ac5d6cb42ca4876e Mon Sep 17 00:00:00 2001 From: Laurenz Date: Tue, 8 Feb 2022 16:39:37 +0100 Subject: Set rules for everything --- src/util/mod.rs | 2 ++ src/util/prehashed.rs | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/util/prehashed.rs (limited to 'src/util') diff --git a/src/util/mod.rs b/src/util/mod.rs index 32ec8dc4..84bd1aa1 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -3,9 +3,11 @@ #[macro_use] mod eco_string; mod mac_roman; +mod prehashed; pub use eco_string::EcoString; pub use mac_roman::decode_mac_roman; +pub use prehashed::Prehashed; use std::cell::RefMut; use std::cmp::Ordering; diff --git a/src/util/prehashed.rs b/src/util/prehashed.rs new file mode 100644 index 00000000..bab1c8f8 --- /dev/null +++ b/src/util/prehashed.rs @@ -0,0 +1,72 @@ +use std::any::Any; +use std::fmt::{self, Debug, Formatter}; +use std::hash::{Hash, Hasher}; +use std::ops::Deref; + +/// A wrapper around a type that precomputes its hash. +#[derive(Copy, Clone)] +pub struct Prehashed { + /// The precomputed hash. + #[cfg(feature = "layout-cache")] + hash: u64, + /// The wrapped item. + item: T, +} + +impl Prehashed { + /// Compute an item's hash and wrap it. + pub fn new(item: T) -> Self { + Self { + #[cfg(feature = "layout-cache")] + hash: { + // Also hash the TypeId because the type might be converted + // through an unsized coercion. + let mut state = fxhash::FxHasher64::default(); + item.type_id().hash(&mut state); + item.hash(&mut state); + state.finish() + }, + item, + } + } + + /// Return the wrapped value. + pub fn into_iter(self) -> T { + self.item + } +} + +impl Deref for Prehashed { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.item + } +} + +impl Debug for Prehashed { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + self.item.fmt(f) + } +} + +impl Hash for Prehashed { + fn hash(&self, state: &mut H) { + // Hash the node. + #[cfg(feature = "layout-cache")] + state.write_u64(self.hash); + #[cfg(not(feature = "layout-cache"))] + self.item.hash(state); + } +} + +impl Eq for Prehashed {} + +impl PartialEq for Prehashed { + fn eq(&self, other: &Self) -> bool { + #[cfg(feature = "layout-cache")] + return self.hash == other.hash; + #[cfg(not(feature = "layout-cache"))] + self.item.eq(&other.item) + } +} -- cgit v1.2.3