Skip to content

Commit ba8aca9

Browse files
committed
Add Prehashed::update
1 parent 19cb913 commit ba8aca9

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/prehashed.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,19 +37,35 @@ impl<T: Hash + 'static> Prehashed<T> {
3737
/// Compute an item's hash and wrap it.
3838
#[inline]
3939
pub fn new(item: T) -> Self {
40-
// Also hash the TypeId because the type might be converted
41-
// through an unsized coercion.
42-
let mut state = SipHasher::new();
43-
item.type_id().hash(&mut state);
44-
item.hash(&mut state);
45-
Self { hash: state.finish128().as_u128(), item }
40+
Self { hash: hash(&item), item }
4641
}
4742

4843
/// Return the wrapped value.
4944
#[inline]
5045
pub fn into_inner(self) -> T {
5146
self.item
5247
}
48+
49+
/// Update the wrapped value and recompute the hash.
50+
#[inline]
51+
pub fn update<F, U>(&mut self, f: F) -> U
52+
where
53+
F: FnOnce(&mut T) -> U,
54+
{
55+
let output = f(&mut self.item);
56+
self.hash = hash(&self.item);
57+
output
58+
}
59+
}
60+
61+
/// Hash the item.
62+
fn hash<T: Hash + 'static>(item: &T) -> u128 {
63+
// Also hash the TypeId because the type might be converted
64+
// through an unsized coercion.
65+
let mut state = SipHasher::new();
66+
item.type_id().hash(&mut state);
67+
item.hash(&mut state);
68+
state.finish128().as_u128()
5369
}
5470

5571
impl<T: ?Sized> Deref for Prehashed<T> {

0 commit comments

Comments
 (0)