Skip to content

Commit c2c1910

Browse files
committed
Implement Hash for raw pointers to unsized types
1 parent 4c053db commit c2c1910

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/libcore/hash/mod.rs

+24-4
Original file line numberDiff line numberDiff line change
@@ -665,16 +665,36 @@ mod impls {
665665
}
666666

667667
#[stable(feature = "rust1", since = "1.0.0")]
668-
impl<T> Hash for *const T {
668+
impl<T: ?Sized> Hash for *const T {
669669
fn hash<H: Hasher>(&self, state: &mut H) {
670-
state.write_usize(*self as usize)
670+
if mem::size_of::<Self>() == mem::size_of::<usize>() {
671+
// Thin pointer
672+
state.write_usize(*self as *const () as usize);
673+
} else {
674+
// Fat pointer
675+
let (a, b) = unsafe {
676+
*(self as *const Self as *const (usize, usize))
677+
};
678+
state.write_usize(a);
679+
state.write_usize(b);
680+
}
671681
}
672682
}
673683

674684
#[stable(feature = "rust1", since = "1.0.0")]
675-
impl<T> Hash for *mut T {
685+
impl<T: ?Sized> Hash for *mut T {
676686
fn hash<H: Hasher>(&self, state: &mut H) {
677-
state.write_usize(*self as usize)
687+
if mem::size_of::<Self>() == mem::size_of::<usize>() {
688+
// Thin pointer
689+
state.write_usize(*self as *const () as usize);
690+
} else {
691+
// Fat pointer
692+
let (a, b) = unsafe {
693+
*(self as *const Self as *const (usize, usize))
694+
};
695+
state.write_usize(a);
696+
state.write_usize(b);
697+
}
678698
}
679699
}
680700
}

src/libcore/tests/hash/mod.rs

+8
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,14 @@ fn test_writer_hasher() {
7979

8080
let ptr = 5_usize as *mut i32;
8181
assert_eq!(hash(&ptr), 5);
82+
83+
let cs: &mut [u8] = &mut [1, 2, 3];
84+
let ptr = cs.as_ptr();
85+
let slice_ptr = cs as *const [u8];
86+
assert_eq!(hash(&slice_ptr), hash(&ptr) + cs.len() as u64);
87+
88+
let slice_ptr = cs as *mut [u8];
89+
assert_eq!(hash(&slice_ptr), hash(&ptr) + cs.len() as u64);
8290
}
8391

8492
struct Custom { hash: u64 }

0 commit comments

Comments
 (0)