Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Hash for raw pointers to unsized types #45483

Merged
merged 1 commit into from
Oct 26, 2017
Merged
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
28 changes: 24 additions & 4 deletions src/libcore/hash/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -665,16 +665,36 @@ mod impls {
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Hash for *const T {
impl<T: ?Sized> Hash for *const T {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_usize(*self as usize)
if mem::size_of::<Self>() == mem::size_of::<usize>() {
// Thin pointer
state.write_usize(*self as *const () as usize);
} else {
// Fat pointer
let (a, b) = unsafe {
*(self as *const Self as *const (usize, usize))
};
state.write_usize(a);
state.write_usize(b);
}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Hash for *mut T {
impl<T: ?Sized> Hash for *mut T {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_usize(*self as usize)
if mem::size_of::<Self>() == mem::size_of::<usize>() {
// Thin pointer
state.write_usize(*self as *const () as usize);
} else {
// Fat pointer
let (a, b) = unsafe {
*(self as *const Self as *const (usize, usize))
};
state.write_usize(a);
state.write_usize(b);
}
}
}
}
8 changes: 8 additions & 0 deletions src/libcore/tests/hash/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ fn test_writer_hasher() {

let ptr = 5_usize as *mut i32;
assert_eq!(hash(&ptr), 5);

let cs: &mut [u8] = &mut [1, 2, 3];
let ptr = cs.as_ptr();
let slice_ptr = cs as *const [u8];
assert_eq!(hash(&slice_ptr), hash(&ptr) + cs.len() as u64);

let slice_ptr = cs as *mut [u8];
assert_eq!(hash(&slice_ptr), hash(&ptr) + cs.len() as u64);
}

struct Custom { hash: u64 }
Expand Down