Skip to content

Commit 3802d57

Browse files
committed
Mention the Borrow guarantee on the Hash implementations for Array and Vec
To remind people like me who forget about it and send PRs to make them different, and to (probably) get a test failure if the code is changed to no longer uphold it.
1 parent 84b1005 commit 3802d57

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2407,6 +2407,23 @@ impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
24072407
}
24082408
}
24092409

2410+
/// The hash of a vector is the same as that of the corresponding slice,
2411+
/// as required by the `core::borrow::Borrow` implementation.
2412+
///
2413+
/// ```
2414+
/// use std::hash::{BuildHasher, Hash, Hasher};
2415+
///
2416+
/// fn hash_of(x: impl Hash, b: &impl BuildHasher) -> u64 {
2417+
/// let mut h = b.build_hasher();
2418+
/// x.hash(&mut h);
2419+
/// h.finish()
2420+
/// }
2421+
///
2422+
/// let b = std::collections::hash_map::RandomState::new();
2423+
/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2424+
/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2425+
/// assert_eq!(hash_of(v, &b), hash_of(s, &b));
2426+
/// ```
24102427
#[stable(feature = "rust1", since = "1.0.0")]
24112428
impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
24122429
#[inline]

library/core/src/array/mod.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,23 @@ impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
139139
}
140140
}
141141

142+
/// The hash of an array is the same as that of the corresponding slice,
143+
/// as required by the `Borrow` implementation.
144+
///
145+
/// ```
146+
/// use std::hash::{BuildHasher, Hash, Hasher};
147+
///
148+
/// fn hash_of(x: impl Hash, b: &impl BuildHasher) -> u64 {
149+
/// let mut h = b.build_hasher();
150+
/// x.hash(&mut h);
151+
/// h.finish()
152+
/// }
153+
///
154+
/// let b = std::collections::hash_map::RandomState::new();
155+
/// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
156+
/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
157+
/// assert_eq!(hash_of(a, &b), hash_of(s, &b));
158+
/// ```
142159
#[stable(feature = "rust1", since = "1.0.0")]
143160
impl<T: Hash, const N: usize> Hash for [T; N] {
144161
fn hash<H: hash::Hasher>(&self, state: &mut H) {

0 commit comments

Comments
 (0)