blob: bab1c8f80c0209865f85967bef0499ba1748e0a9 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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<T: ?Sized> {
/// The precomputed hash.
#[cfg(feature = "layout-cache")]
hash: u64,
/// The wrapped item.
item: T,
}
impl<T: Hash + 'static> Prehashed<T> {
/// 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<T: ?Sized> Deref for Prehashed<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.item
}
}
impl<T: Debug + ?Sized> Debug for Prehashed<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.item.fmt(f)
}
}
impl<T: Hash + ?Sized> Hash for Prehashed<T> {
fn hash<H: Hasher>(&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<T: Eq + ?Sized> Eq for Prehashed<T> {}
impl<T: PartialEq + ?Sized> PartialEq for Prehashed<T> {
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)
}
}
|