Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,17 @@ impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
}
}

/// Note that `Hash` for arrays provides no guarantees on its behavior other
/// than the consistency with `Eq` required by the trait, and its implementation
/// may change between rust versions.
///
/// For example, the hash of the array `[x, y, z]` may or may not be the same as
/// the hash of the tuple `(x, y, z)`, and the hash of the array `[x, y, z]` may
/// or may not be the same as the hash of the vector `vec![x, y, z]`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may be in conflict with requirements of the Borrow trait which is implemented for arrays and slices.

Copy link
Contributor

@camsteffen camsteffen Jun 8, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a playground. Shows the problem and a workaround.

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Hash, const N: usize> Hash for [T; N] {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Hash::hash(&self[..], state)
Hash::hash_slice(&self[..], state)
}
}

Expand Down
21 changes: 21 additions & 0 deletions library/core/tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,24 @@ fn cell_allows_array_cycle() {
b3.a[0].set(Some(&b1));
b3.a[1].set(Some(&b2));
}

#[test]
fn hashing_array_does_not_hash_length() {
use core::hash::{Hash, Hasher};

struct PanicOnHashUsize(usize);
impl Hasher for PanicOnHashUsize {
fn finish(&self) -> u64 {
self.0 as _
}
fn write(&mut self, bytes: &[u8]) {
assert!(bytes.len() < core::mem::size_of::<usize>());
self.0 += bytes.len();
}
}

let mut h = PanicOnHashUsize(0);
let a: [u8; 1] = [42];
a.hash(&mut h);
assert_eq!(h.finish(), 1);
}