From 3802d573c36902dbab68199beee3041514efd8bd Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Tue, 8 Jun 2021 08:51:44 -0700 Subject: [PATCH] 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. --- library/alloc/src/vec/mod.rs | 17 +++++++++++++++++ library/core/src/array/mod.rs | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 105c60e7bf085..aff27b7af306d 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -2407,6 +2407,23 @@ impl Clone for Vec { } } +/// The hash of a vector is the same as that of the corresponding slice, +/// as required by the `core::borrow::Borrow` implementation. +/// +/// ``` +/// use std::hash::{BuildHasher, Hash, Hasher}; +/// +/// fn hash_of(x: impl Hash, b: &impl BuildHasher) -> u64 { +/// let mut h = b.build_hasher(); +/// x.hash(&mut h); +/// h.finish() +/// } +/// +/// let b = std::collections::hash_map::RandomState::new(); +/// let v: Vec = vec![0xa8, 0x3c, 0x09]; +/// let s: &[u8] = &[0xa8, 0x3c, 0x09]; +/// assert_eq!(hash_of(v, &b), hash_of(s, &b)); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] impl Hash for Vec { #[inline] diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index e25d006d213c7..aa7f71cf85b5f 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -139,6 +139,23 @@ impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] { } } +/// The hash of an array is the same as that of the corresponding slice, +/// as required by the `Borrow` implementation. +/// +/// ``` +/// use std::hash::{BuildHasher, Hash, Hasher}; +/// +/// fn hash_of(x: impl Hash, b: &impl BuildHasher) -> u64 { +/// let mut h = b.build_hasher(); +/// x.hash(&mut h); +/// h.finish() +/// } +/// +/// let b = std::collections::hash_map::RandomState::new(); +/// let a: [u8; 3] = [0xa8, 0x3c, 0x09]; +/// let s: &[u8] = &[0xa8, 0x3c, 0x09]; +/// assert_eq!(hash_of(a, &b), hash_of(s, &b)); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] impl Hash for [T; N] { fn hash(&self, state: &mut H) {