1 //! Generic hashing support.
3 //! This module provides a generic way to compute the [hash] of a value.
4 //! Hashes are most commonly used with [`HashMap`] and [`HashSet`].
6 //! [hash]: https://en.wikipedia.org/wiki/Hash_function
7 //! [`HashMap`]: ../../std/collections/struct.HashMap.html
8 //! [`HashSet`]: ../../std/collections/struct.HashSet.html
10 //! The simplest way to make a type hashable is to use `#[derive(Hash)]`:
15 //! use std::collections::hash_map::DefaultHasher;
16 //! use std::hash::{Hash, Hasher};
25 //! let person1 = Person {
27 //! name: "Janet".to_string(),
28 //! phone: 555_666_7777,
30 //! let person2 = Person {
32 //! name: "Bob".to_string(),
33 //! phone: 555_666_7777,
36 //! assert!(calculate_hash(&person1) != calculate_hash(&person2));
38 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
39 //! let mut s = DefaultHasher::new();
45 //! If you need more control over how a value is hashed, you need to implement
46 //! the [`Hash`] trait:
49 //! use std::collections::hash_map::DefaultHasher;
50 //! use std::hash::{Hash, Hasher};
54 //! # #[allow(dead_code)]
59 //! impl Hash for Person {
60 //! fn hash<H: Hasher>(&self, state: &mut H) {
61 //! self.id.hash(state);
62 //! self.phone.hash(state);
66 //! let person1 = Person {
68 //! name: "Janet".to_string(),
69 //! phone: 555_666_7777,
71 //! let person2 = Person {
73 //! name: "Bob".to_string(),
74 //! phone: 555_666_7777,
77 //! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
79 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
80 //! let mut s = DefaultHasher::new();
86 #![stable(feature = "rust1", since = "1.0.0")]
91 #[stable(feature = "rust1", since = "1.0.0")]
93 pub use self::sip::SipHasher;
95 #[unstable(feature = "hashmap_internals", issue = "none")]
98 pub use self::sip::SipHasher13;
104 /// Types implementing `Hash` are able to be [`hash`]ed with an instance of
107 /// ## Implementing `Hash`
109 /// You can derive `Hash` with `#[derive(Hash)]` if all fields implement `Hash`.
110 /// The resulting hash will be the combination of the values from calling
111 /// [`hash`] on each field.
115 /// struct Rustacean {
121 /// If you need more control over how a value is hashed, you can of course
122 /// implement the `Hash` trait yourself:
125 /// use std::hash::{Hash, Hasher};
133 /// impl Hash for Person {
134 /// fn hash<H: Hasher>(&self, state: &mut H) {
135 /// self.id.hash(state);
136 /// self.phone.hash(state);
141 /// ## `Hash` and `Eq`
143 /// When implementing both `Hash` and [`Eq`], it is important that the following
147 /// k1 == k2 -> hash(k1) == hash(k2)
150 /// In other words, if two keys are equal, their hashes must also be equal.
151 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
153 /// Thankfully, you won't need to worry about upholding this property when
154 /// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
156 /// ## Prefix collisions
158 /// Implementations of `hash` should ensure that the data they
159 /// pass to the `Hasher` are prefix-free. That is,
160 /// unequal values should cause two different sequences of values to be written,
161 /// and neither of the two sequences should be a prefix of the other.
163 /// For example, the standard implementation of [`Hash` for `&str`][impl] passes an extra
164 /// `0xFF` byte to the `Hasher` so that the values `("ab", "c")` and `("a",
165 /// "bc")` hash differently.
169 /// Due to differences in endianness and type sizes, data fed by `Hash` to a `Hasher`
170 /// should not be considered portable across platforms. Additionally the data passed by most
171 /// standard library types should not be considered stable between compiler versions.
173 /// This means tests shouldn't probe hard-coded hash values or data fed to a `Hasher` and
174 /// instead should check consistency with `Eq`.
176 /// Serialization formats intended to be portable between platforms or compiler versions should
177 /// either avoid encoding hashes or only rely on `Hash` and `Hasher` implementations that
178 /// provide additional guarantees.
180 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
181 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
182 /// [`hash`]: Hash::hash
183 /// [impl]: ../../std/primitive.str.html#impl-Hash
184 #[stable(feature = "rust1", since = "1.0.0")]
185 #[rustc_diagnostic_item = "Hash"]
187 /// Feeds this value into the given [`Hasher`].
192 /// use std::collections::hash_map::DefaultHasher;
193 /// use std::hash::{Hash, Hasher};
195 /// let mut hasher = DefaultHasher::new();
196 /// 7920.hash(&mut hasher);
197 /// println!("Hash is {:x}!", hasher.finish());
199 #[stable(feature = "rust1", since = "1.0.0")]
200 fn hash<H: Hasher>(&self, state: &mut H);
202 /// Feeds a slice of this type into the given [`Hasher`].
204 /// This method is meant as a convenience, but its implementation is
205 /// also explicitly left unspecified. It isn't guaranteed to be
206 /// equivalent to repeated calls of [`hash`] and implementations of
207 /// [`Hash`] should keep that in mind and call [`hash`] themselves
208 /// if the slice isn't treated as a whole unit in the [`PartialEq`]
211 /// For example, a [`VecDeque`] implementation might naïvely call
212 /// [`as_slices`] and then [`hash_slice`] on each slice, but this
213 /// is wrong since the two slices can change with a call to
214 /// [`make_contiguous`] without affecting the [`PartialEq`]
215 /// result. Since these slices aren't treated as singular
216 /// units, and instead part of a larger deque, this method cannot
222 /// use std::collections::hash_map::DefaultHasher;
223 /// use std::hash::{Hash, Hasher};
225 /// let mut hasher = DefaultHasher::new();
226 /// let numbers = [6, 28, 496, 8128];
227 /// Hash::hash_slice(&numbers, &mut hasher);
228 /// println!("Hash is {:x}!", hasher.finish());
231 /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html
232 /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices
233 /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous
234 /// [`hash`]: Hash::hash
235 /// [`hash_slice`]: Hash::hash_slice
236 #[stable(feature = "hash_slice", since = "1.3.0")]
237 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
247 // Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
248 pub(crate) mod macros {
249 /// Derive macro generating an impl of the trait `Hash`.
250 #[rustc_builtin_macro]
251 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
252 #[allow_internal_unstable(core_intrinsics)]
253 pub macro Hash($item:item) {
254 /* compiler built-in */
257 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
259 pub use macros::Hash;
261 /// A trait for hashing an arbitrary stream of bytes.
263 /// Instances of `Hasher` usually represent state that is changed while hashing
266 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
267 /// (with [`finish`]), and writing integers as well as slices of bytes into an
268 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
269 /// instances are used in conjunction with the [`Hash`] trait.
271 /// This trait makes no assumptions about how the various `write_*` methods are
272 /// defined and implementations of [`Hash`] should not assume that they work one
273 /// way or another. You cannot assume, for example, that a [`write_u32`] call is
274 /// equivalent to four calls of [`write_u8`].
279 /// use std::collections::hash_map::DefaultHasher;
280 /// use std::hash::Hasher;
282 /// let mut hasher = DefaultHasher::new();
284 /// hasher.write_u32(1989);
285 /// hasher.write_u8(11);
286 /// hasher.write_u8(9);
287 /// hasher.write(b"Huh?");
289 /// println!("Hash is {:x}!", hasher.finish());
292 /// [`finish`]: Hasher::finish
293 /// [`write`]: Hasher::write
294 /// [`write_u8`]: Hasher::write_u8
295 /// [`write_u32`]: Hasher::write_u32
296 #[stable(feature = "rust1", since = "1.0.0")]
298 /// Returns the hash value for the values written so far.
300 /// Despite its name, the method does not reset the hasher’s internal
301 /// state. Additional [`write`]s will continue from the current value.
302 /// If you need to start a fresh hash value, you will have to create
308 /// use std::collections::hash_map::DefaultHasher;
309 /// use std::hash::Hasher;
311 /// let mut hasher = DefaultHasher::new();
312 /// hasher.write(b"Cool!");
314 /// println!("Hash is {:x}!", hasher.finish());
317 /// [`write`]: Hasher::write
318 #[stable(feature = "rust1", since = "1.0.0")]
319 fn finish(&self) -> u64;
321 /// Writes some data into this `Hasher`.
326 /// use std::collections::hash_map::DefaultHasher;
327 /// use std::hash::Hasher;
329 /// let mut hasher = DefaultHasher::new();
330 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
332 /// hasher.write(&data);
334 /// println!("Hash is {:x}!", hasher.finish());
337 /// # Note to Implementers
339 /// You generally should not do length-prefixing as part of implementing
340 /// this method. It's up to the [`Hash`] implementation to call
341 /// [`Hasher::write_length_prefix`] before sequences that need it.
342 #[stable(feature = "rust1", since = "1.0.0")]
343 fn write(&mut self, bytes: &[u8]);
345 /// Writes a single `u8` into this hasher.
347 #[stable(feature = "hasher_write", since = "1.3.0")]
348 fn write_u8(&mut self, i: u8) {
351 /// Writes a single `u16` into this hasher.
353 #[stable(feature = "hasher_write", since = "1.3.0")]
354 fn write_u16(&mut self, i: u16) {
355 self.write(&i.to_ne_bytes())
357 /// Writes a single `u32` into this hasher.
359 #[stable(feature = "hasher_write", since = "1.3.0")]
360 fn write_u32(&mut self, i: u32) {
361 self.write(&i.to_ne_bytes())
363 /// Writes a single `u64` into this hasher.
365 #[stable(feature = "hasher_write", since = "1.3.0")]
366 fn write_u64(&mut self, i: u64) {
367 self.write(&i.to_ne_bytes())
369 /// Writes a single `u128` into this hasher.
371 #[stable(feature = "i128", since = "1.26.0")]
372 fn write_u128(&mut self, i: u128) {
373 self.write(&i.to_ne_bytes())
375 /// Writes a single `usize` into this hasher.
377 #[stable(feature = "hasher_write", since = "1.3.0")]
378 fn write_usize(&mut self, i: usize) {
379 self.write(&i.to_ne_bytes())
382 /// Writes a single `i8` into this hasher.
384 #[stable(feature = "hasher_write", since = "1.3.0")]
385 fn write_i8(&mut self, i: i8) {
386 self.write_u8(i as u8)
388 /// Writes a single `i16` into this hasher.
390 #[stable(feature = "hasher_write", since = "1.3.0")]
391 fn write_i16(&mut self, i: i16) {
392 self.write_u16(i as u16)
394 /// Writes a single `i32` into this hasher.
396 #[stable(feature = "hasher_write", since = "1.3.0")]
397 fn write_i32(&mut self, i: i32) {
398 self.write_u32(i as u32)
400 /// Writes a single `i64` into this hasher.
402 #[stable(feature = "hasher_write", since = "1.3.0")]
403 fn write_i64(&mut self, i: i64) {
404 self.write_u64(i as u64)
406 /// Writes a single `i128` into this hasher.
408 #[stable(feature = "i128", since = "1.26.0")]
409 fn write_i128(&mut self, i: i128) {
410 self.write_u128(i as u128)
412 /// Writes a single `isize` into this hasher.
414 #[stable(feature = "hasher_write", since = "1.3.0")]
415 fn write_isize(&mut self, i: isize) {
416 self.write_usize(i as usize)
419 /// Writes a length prefix into this hasher, as part of being prefix-free.
421 /// If you're implementing [`Hash`] for a custom collection, call this before
422 /// writing its contents to this `Hasher`. That way
423 /// `(collection![1, 2, 3], collection![4, 5])` and
424 /// `(collection![1, 2], collection![3, 4, 5])` will provide different
425 /// sequences of values to the `Hasher`
427 /// The `impl<T> Hash for [T]` includes a call to this method, so if you're
428 /// hashing a slice (or array or vector) via its `Hash::hash` method,
429 /// you should **not** call this yourself.
431 /// This method is only for providing domain separation. If you want to
432 /// hash a `usize` that represents part of the *data*, then it's important
433 /// that you pass it to [`Hasher::write_usize`] instead of to this method.
438 /// #![feature(hasher_prefixfree_extras)]
439 /// # // Stubs to make the `impl` below pass the compiler
440 /// # struct MyCollection<T>(Option<T>);
441 /// # impl<T> MyCollection<T> {
442 /// # fn len(&self) -> usize { todo!() }
444 /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
446 /// # type IntoIter = std::iter::Empty<T>;
447 /// # fn into_iter(self) -> Self::IntoIter { todo!() }
450 /// use std::hash::{Hash, Hasher};
451 /// impl<T: Hash> Hash for MyCollection<T> {
452 /// fn hash<H: Hasher>(&self, state: &mut H) {
453 /// state.write_length_prefix(self.len());
454 /// for elt in self {
461 /// # Note to Implementers
463 /// If you've decided that your `Hasher` is willing to be susceptible to
464 /// Hash-DoS attacks, then you might consider skipping hashing some or all
465 /// of the `len` provided in the name of increased performance.
467 #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
468 fn write_length_prefix(&mut self, len: usize) {
469 self.write_usize(len);
472 /// Writes a single `str` into this hasher.
474 /// If you're implementing [`Hash`], you generally do not need to call this,
475 /// as the `impl Hash for str` does, so you should prefer that instead.
477 /// This includes the domain separator for prefix-freedom, so you should
478 /// **not** call `Self::write_length_prefix` before calling this.
480 /// # Note to Implementers
482 /// There are at least two reasonable default ways to implement this.
483 /// Which one will be the default is not yet decided, so for now
484 /// you probably want to override it specifically.
486 /// ## The general answer
488 /// It's always correct to implement this with a length prefix:
491 /// # #![feature(hasher_prefixfree_extras)]
493 /// # impl std::hash::Hasher for Foo {
494 /// # fn finish(&self) -> u64 { unimplemented!() }
495 /// # fn write(&mut self, _bytes: &[u8]) { unimplemented!() }
496 /// fn write_str(&mut self, s: &str) {
497 /// self.write_length_prefix(s.len());
498 /// self.write(s.as_bytes());
503 /// And, if your `Hasher` works in `usize` chunks, this is likely a very
504 /// efficient way to do it, as anything more complicated may well end up
505 /// slower than just running the round with the length.
507 /// ## If your `Hasher` works byte-wise
509 /// One nice thing about `str` being UTF-8 is that the `b'\xFF'` byte
510 /// never happens. That means that you can append that to the byte stream
511 /// being hashed and maintain prefix-freedom:
514 /// # #![feature(hasher_prefixfree_extras)]
516 /// # impl std::hash::Hasher for Foo {
517 /// # fn finish(&self) -> u64 { unimplemented!() }
518 /// # fn write(&mut self, _bytes: &[u8]) { unimplemented!() }
519 /// fn write_str(&mut self, s: &str) {
520 /// self.write(s.as_bytes());
521 /// self.write_u8(0xff);
526 /// This does require that your implementation not add extra padding, and
527 /// thus generally requires that you maintain a buffer, running a round
528 /// only once that buffer is full (or `finish` is called).
530 /// That's because if `write` pads data out to a fixed chunk size, it's
531 /// likely that it does it in such a way that `"a"` and `"a\x00"` would
532 /// end up hashing the same sequence of things, introducing conflicts.
534 #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
535 fn write_str(&mut self, s: &str) {
536 self.write(s.as_bytes());
541 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
542 impl<H: Hasher + ?Sized> Hasher for &mut H {
543 fn finish(&self) -> u64 {
546 fn write(&mut self, bytes: &[u8]) {
547 (**self).write(bytes)
549 fn write_u8(&mut self, i: u8) {
552 fn write_u16(&mut self, i: u16) {
553 (**self).write_u16(i)
555 fn write_u32(&mut self, i: u32) {
556 (**self).write_u32(i)
558 fn write_u64(&mut self, i: u64) {
559 (**self).write_u64(i)
561 fn write_u128(&mut self, i: u128) {
562 (**self).write_u128(i)
564 fn write_usize(&mut self, i: usize) {
565 (**self).write_usize(i)
567 fn write_i8(&mut self, i: i8) {
570 fn write_i16(&mut self, i: i16) {
571 (**self).write_i16(i)
573 fn write_i32(&mut self, i: i32) {
574 (**self).write_i32(i)
576 fn write_i64(&mut self, i: i64) {
577 (**self).write_i64(i)
579 fn write_i128(&mut self, i: i128) {
580 (**self).write_i128(i)
582 fn write_isize(&mut self, i: isize) {
583 (**self).write_isize(i)
585 fn write_length_prefix(&mut self, len: usize) {
586 (**self).write_length_prefix(len)
588 fn write_str(&mut self, s: &str) {
589 (**self).write_str(s)
593 /// A trait for creating instances of [`Hasher`].
595 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
596 /// [`Hasher`]s for each key such that they are hashed independently of one
597 /// another, since [`Hasher`]s contain state.
599 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
600 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
601 /// is fed into each hasher, the same output will also be generated.
606 /// use std::collections::hash_map::RandomState;
607 /// use std::hash::{BuildHasher, Hasher};
609 /// let s = RandomState::new();
610 /// let mut hasher_1 = s.build_hasher();
611 /// let mut hasher_2 = s.build_hasher();
613 /// hasher_1.write_u32(8128);
614 /// hasher_2.write_u32(8128);
616 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
619 /// [`build_hasher`]: BuildHasher::build_hasher
620 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
621 #[stable(since = "1.7.0", feature = "build_hasher")]
622 pub trait BuildHasher {
623 /// Type of the hasher that will be created.
624 #[stable(since = "1.7.0", feature = "build_hasher")]
627 /// Creates a new hasher.
629 /// Each call to `build_hasher` on the same instance should produce identical
635 /// use std::collections::hash_map::RandomState;
636 /// use std::hash::BuildHasher;
638 /// let s = RandomState::new();
639 /// let new_s = s.build_hasher();
641 #[stable(since = "1.7.0", feature = "build_hasher")]
642 fn build_hasher(&self) -> Self::Hasher;
644 /// Calculates the hash of a single value.
646 /// This is intended as a convenience for code which *consumes* hashes, such
647 /// as the implementation of a hash table or in unit tests that check
648 /// whether a custom [`Hash`] implementation behaves as expected.
650 /// This must not be used in any code which *creates* hashes, such as in an
651 /// implementation of [`Hash`]. The way to create a combined hash of
652 /// multiple values is to call [`Hash::hash`] multiple times using the same
653 /// [`Hasher`], not to call this method repeatedly and combine the results.
658 /// #![feature(build_hasher_simple_hash_one)]
660 /// use std::cmp::{max, min};
661 /// use std::hash::{BuildHasher, Hash, Hasher};
662 /// struct OrderAmbivalentPair<T: Ord>(T, T);
663 /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
664 /// fn hash<H: Hasher>(&self, hasher: &mut H) {
665 /// min(&self.0, &self.1).hash(hasher);
666 /// max(&self.0, &self.1).hash(hasher);
670 /// // Then later, in a `#[test]` for the type...
671 /// let bh = std::collections::hash_map::RandomState::new();
673 /// bh.hash_one(OrderAmbivalentPair(1, 2)),
674 /// bh.hash_one(OrderAmbivalentPair(2, 1))
677 /// bh.hash_one(OrderAmbivalentPair(10, 2)),
678 /// bh.hash_one(&OrderAmbivalentPair(2, 10))
681 #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
682 fn hash_one<T: Hash>(&self, x: T) -> u64
686 let mut hasher = self.build_hasher();
692 /// Used to create a default [`BuildHasher`] instance for types that implement
693 /// [`Hasher`] and [`Default`].
695 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
696 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
699 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
700 /// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
701 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
702 /// [`Default`] instances themselves.
706 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
710 /// use std::collections::HashMap;
711 /// use std::hash::{BuildHasherDefault, Hasher};
713 /// #[derive(Default)]
716 /// impl Hasher for MyHasher {
717 /// fn write(&mut self, bytes: &[u8]) {
718 /// // Your hashing algorithm goes here!
722 /// fn finish(&self) -> u64 {
723 /// // Your hashing algorithm goes here!
728 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
730 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
733 /// [method.default]: BuildHasherDefault::default
734 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
735 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
736 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
737 #[stable(since = "1.7.0", feature = "build_hasher")]
738 pub struct BuildHasherDefault<H>(marker::PhantomData<fn() -> H>);
740 #[stable(since = "1.9.0", feature = "core_impl_debug")]
741 impl<H> fmt::Debug for BuildHasherDefault<H> {
742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743 f.debug_struct("BuildHasherDefault").finish()
747 #[stable(since = "1.7.0", feature = "build_hasher")]
748 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
751 fn build_hasher(&self) -> H {
756 #[stable(since = "1.7.0", feature = "build_hasher")]
757 impl<H> Clone for BuildHasherDefault<H> {
758 fn clone(&self) -> BuildHasherDefault<H> {
759 BuildHasherDefault(marker::PhantomData)
763 #[stable(since = "1.7.0", feature = "build_hasher")]
764 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
765 impl<H> const Default for BuildHasherDefault<H> {
766 fn default() -> BuildHasherDefault<H> {
767 BuildHasherDefault(marker::PhantomData)
771 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
772 impl<H> PartialEq for BuildHasherDefault<H> {
773 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
778 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
779 impl<H> Eq for BuildHasherDefault<H> {}
787 macro_rules! impl_write {
788 ($(($ty:ident, $meth:ident),)*) => {$(
789 #[stable(feature = "rust1", since = "1.0.0")]
792 fn hash<H: Hasher>(&self, state: &mut H) {
797 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
798 let newlen = data.len() * mem::size_of::<$ty>();
799 let ptr = data.as_ptr() as *const u8;
800 // SAFETY: `ptr` is valid and aligned, as this macro is only used
801 // for numeric primitives which have no padding. The new slice only
802 // spans across `data` and is never mutated, and its total size is the
803 // same as the original `data` so it can't be over `isize::MAX`.
804 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
815 (usize, write_usize),
820 (isize, write_isize),
825 #[stable(feature = "rust1", since = "1.0.0")]
828 fn hash<H: Hasher>(&self, state: &mut H) {
829 state.write_u8(*self as u8)
833 #[stable(feature = "rust1", since = "1.0.0")]
836 fn hash<H: Hasher>(&self, state: &mut H) {
837 state.write_u32(*self as u32)
841 #[stable(feature = "rust1", since = "1.0.0")]
844 fn hash<H: Hasher>(&self, state: &mut H) {
845 state.write_str(self);
849 #[stable(feature = "never_hash", since = "1.29.0")]
852 fn hash<H: Hasher>(&self, _: &mut H) {
857 macro_rules! impl_hash_tuple {
859 #[stable(feature = "rust1", since = "1.0.0")]
862 fn hash<H: Hasher>(&self, _state: &mut H) {}
866 ( $($name:ident)+) => (
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
869 #[allow(non_snake_case)]
871 fn hash<S: Hasher>(&self, state: &mut S) {
872 let ($(ref $name,)+) = *self;
873 $($name.hash(state);)+
879 macro_rules! last_type {
880 ($a:ident,) => { $a };
881 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
885 impl_hash_tuple! { A }
886 impl_hash_tuple! { A B }
887 impl_hash_tuple! { A B C }
888 impl_hash_tuple! { A B C D }
889 impl_hash_tuple! { A B C D E }
890 impl_hash_tuple! { A B C D E F }
891 impl_hash_tuple! { A B C D E F G }
892 impl_hash_tuple! { A B C D E F G H }
893 impl_hash_tuple! { A B C D E F G H I }
894 impl_hash_tuple! { A B C D E F G H I J }
895 impl_hash_tuple! { A B C D E F G H I J K }
896 impl_hash_tuple! { A B C D E F G H I J K L }
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<T: Hash> Hash for [T] {
901 fn hash<H: Hasher>(&self, state: &mut H) {
902 state.write_length_prefix(self.len());
903 Hash::hash_slice(self, state)
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<T: ?Sized + Hash> Hash for &T {
910 fn hash<H: Hasher>(&self, state: &mut H) {
911 (**self).hash(state);
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl<T: ?Sized + Hash> Hash for &mut T {
918 fn hash<H: Hasher>(&self, state: &mut H) {
919 (**self).hash(state);
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl<T: ?Sized> Hash for *const T {
926 fn hash<H: Hasher>(&self, state: &mut H) {
927 let (address, metadata) = self.to_raw_parts();
928 state.write_usize(address.addr());
929 metadata.hash(state);
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<T: ?Sized> Hash for *mut T {
936 fn hash<H: Hasher>(&self, state: &mut H) {
937 let (address, metadata) = self.to_raw_parts();
938 state.write_usize(address.addr());
939 metadata.hash(state);