]> git.lizzy.rs Git - rust.git/blob - library/core/src/hash/mod.rs
Rollup merge of #89468 - FabianWolff:issue-89358, r=jackh726
[rust.git] / library / core / src / hash / mod.rs
1 //! Generic hashing support.
2 //!
3 //! This module provides a generic way to compute the [hash] of a value.
4 //! Hashes are most commonly used with [`HashMap`] and [`HashSet`].
5 //!
6 //! [hash]: https://en.wikipedia.org/wiki/Hash_function
7 //! [`HashMap`]: ../../std/collections/struct.HashMap.html
8 //! [`HashSet`]: ../../std/collections/struct.HashSet.html
9 //!
10 //! The simplest way to make a type hashable is to use `#[derive(Hash)]`:
11 //!
12 //! # Examples
13 //!
14 //! ```rust
15 //! use std::collections::hash_map::DefaultHasher;
16 //! use std::hash::{Hash, Hasher};
17 //!
18 //! #[derive(Hash)]
19 //! struct Person {
20 //!     id: u32,
21 //!     name: String,
22 //!     phone: u64,
23 //! }
24 //!
25 //! let person1 = Person {
26 //!     id: 5,
27 //!     name: "Janet".to_string(),
28 //!     phone: 555_666_7777,
29 //! };
30 //! let person2 = Person {
31 //!     id: 5,
32 //!     name: "Bob".to_string(),
33 //!     phone: 555_666_7777,
34 //! };
35 //!
36 //! assert!(calculate_hash(&person1) != calculate_hash(&person2));
37 //!
38 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
39 //!     let mut s = DefaultHasher::new();
40 //!     t.hash(&mut s);
41 //!     s.finish()
42 //! }
43 //! ```
44 //!
45 //! If you need more control over how a value is hashed, you need to implement
46 //! the [`Hash`] trait:
47 //!
48 //! ```rust
49 //! use std::collections::hash_map::DefaultHasher;
50 //! use std::hash::{Hash, Hasher};
51 //!
52 //! struct Person {
53 //!     id: u32,
54 //!     # #[allow(dead_code)]
55 //!     name: String,
56 //!     phone: u64,
57 //! }
58 //!
59 //! impl Hash for Person {
60 //!     fn hash<H: Hasher>(&self, state: &mut H) {
61 //!         self.id.hash(state);
62 //!         self.phone.hash(state);
63 //!     }
64 //! }
65 //!
66 //! let person1 = Person {
67 //!     id: 5,
68 //!     name: "Janet".to_string(),
69 //!     phone: 555_666_7777,
70 //! };
71 //! let person2 = Person {
72 //!     id: 5,
73 //!     name: "Bob".to_string(),
74 //!     phone: 555_666_7777,
75 //! };
76 //!
77 //! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
78 //!
79 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
80 //!     let mut s = DefaultHasher::new();
81 //!     t.hash(&mut s);
82 //!     s.finish()
83 //! }
84 //! ```
85
86 #![stable(feature = "rust1", since = "1.0.0")]
87
88 use crate::fmt;
89 use crate::marker;
90
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[allow(deprecated)]
93 pub use self::sip::SipHasher;
94
95 #[unstable(feature = "hashmap_internals", issue = "none")]
96 #[allow(deprecated)]
97 #[doc(hidden)]
98 pub use self::sip::SipHasher13;
99
100 mod sip;
101
102 /// A hashable type.
103 ///
104 /// Types implementing `Hash` are able to be [`hash`]ed with an instance of
105 /// [`Hasher`].
106 ///
107 /// ## Implementing `Hash`
108 ///
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.
112 ///
113 /// ```
114 /// #[derive(Hash)]
115 /// struct Rustacean {
116 ///     name: String,
117 ///     country: String,
118 /// }
119 /// ```
120 ///
121 /// If you need more control over how a value is hashed, you can of course
122 /// implement the `Hash` trait yourself:
123 ///
124 /// ```
125 /// use std::hash::{Hash, Hasher};
126 ///
127 /// struct Person {
128 ///     id: u32,
129 ///     name: String,
130 ///     phone: u64,
131 /// }
132 ///
133 /// impl Hash for Person {
134 ///     fn hash<H: Hasher>(&self, state: &mut H) {
135 ///         self.id.hash(state);
136 ///         self.phone.hash(state);
137 ///     }
138 /// }
139 /// ```
140 ///
141 /// ## `Hash` and `Eq`
142 ///
143 /// When implementing both `Hash` and [`Eq`], it is important that the following
144 /// property holds:
145 ///
146 /// ```text
147 /// k1 == k2 -> hash(k1) == hash(k2)
148 /// ```
149 ///
150 /// In other words, if two keys are equal, their hashes must also be equal.
151 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
152 ///
153 /// Thankfully, you won't need to worry about upholding this property when
154 /// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
155 ///
156 /// ## Prefix collisions
157 ///
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.
162 ///
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.
166 ///
167 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
168 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
169 /// [`hash`]: Hash::hash
170 /// [impl]: ../../std/primitive.str.html#impl-Hash
171 #[stable(feature = "rust1", since = "1.0.0")]
172 #[rustc_diagnostic_item = "Hash"]
173 pub trait Hash {
174     /// Feeds this value into the given [`Hasher`].
175     ///
176     /// # Examples
177     ///
178     /// ```
179     /// use std::collections::hash_map::DefaultHasher;
180     /// use std::hash::{Hash, Hasher};
181     ///
182     /// let mut hasher = DefaultHasher::new();
183     /// 7920.hash(&mut hasher);
184     /// println!("Hash is {:x}!", hasher.finish());
185     /// ```
186     #[stable(feature = "rust1", since = "1.0.0")]
187     fn hash<H: Hasher>(&self, state: &mut H);
188
189     /// Feeds a slice of this type into the given [`Hasher`].
190     ///
191     /// This method is meant as a convenience, but its implementation is
192     /// also explicitly left unspecified. It isn't guaranteed to be
193     /// equivalent to repeated calls of [`hash`] and implementations of
194     /// [`Hash`] should keep that in mind and call [`hash`] themselves
195     /// if the slice isn't treated as a whole unit in the [`PartialEq`]
196     /// implementation.
197     ///
198     /// For example, a [`VecDeque`] implementation might naïvely call
199     /// [`as_slices`] and then [`hash_slice`] on each slice, but this
200     /// is wrong since the two slices can change with a call to
201     /// [`make_contiguous`] without affecting the [`PartialEq`]
202     /// result. Since these slices aren't treated as singular
203     /// units, and instead part of a larger deque, this method cannot
204     /// be used.
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// use std::collections::hash_map::DefaultHasher;
210     /// use std::hash::{Hash, Hasher};
211     ///
212     /// let mut hasher = DefaultHasher::new();
213     /// let numbers = [6, 28, 496, 8128];
214     /// Hash::hash_slice(&numbers, &mut hasher);
215     /// println!("Hash is {:x}!", hasher.finish());
216     /// ```
217     ///
218     /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html
219     /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices
220     /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous
221     /// [`hash`]: Hash::hash
222     /// [`hash_slice`]: Hash::hash_slice
223     #[stable(feature = "hash_slice", since = "1.3.0")]
224     fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
225     where
226         Self: Sized,
227     {
228         for piece in data {
229             piece.hash(state);
230         }
231     }
232 }
233
234 // Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
235 pub(crate) mod macros {
236     /// Derive macro generating an impl of the trait `Hash`.
237     #[rustc_builtin_macro]
238     #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
239     #[allow_internal_unstable(core_intrinsics)]
240     pub macro Hash($item:item) {
241         /* compiler built-in */
242     }
243 }
244 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
245 #[doc(inline)]
246 pub use macros::Hash;
247
248 /// A trait for hashing an arbitrary stream of bytes.
249 ///
250 /// Instances of `Hasher` usually represent state that is changed while hashing
251 /// data.
252 ///
253 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
254 /// (with [`finish`]), and writing integers as well as slices of bytes into an
255 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
256 /// instances are used in conjunction with the [`Hash`] trait.
257 ///
258 /// This trait makes no assumptions about how the various `write_*` methods are
259 /// defined and implementations of [`Hash`] should not assume that they work one
260 /// way or another. You cannot assume, for example, that a [`write_u32`] call is
261 /// equivalent to four calls of [`write_u8`].
262 ///
263 /// # Examples
264 ///
265 /// ```
266 /// use std::collections::hash_map::DefaultHasher;
267 /// use std::hash::Hasher;
268 ///
269 /// let mut hasher = DefaultHasher::new();
270 ///
271 /// hasher.write_u32(1989);
272 /// hasher.write_u8(11);
273 /// hasher.write_u8(9);
274 /// hasher.write(b"Huh?");
275 ///
276 /// println!("Hash is {:x}!", hasher.finish());
277 /// ```
278 ///
279 /// [`finish`]: Hasher::finish
280 /// [`write`]: Hasher::write
281 /// [`write_u8`]: Hasher::write_u8
282 /// [`write_u32`]: Hasher::write_u32
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub trait Hasher {
285     /// Returns the hash value for the values written so far.
286     ///
287     /// Despite its name, the method does not reset the hasher’s internal
288     /// state. Additional [`write`]s will continue from the current value.
289     /// If you need to start a fresh hash value, you will have to create
290     /// a new hasher.
291     ///
292     /// # Examples
293     ///
294     /// ```
295     /// use std::collections::hash_map::DefaultHasher;
296     /// use std::hash::Hasher;
297     ///
298     /// let mut hasher = DefaultHasher::new();
299     /// hasher.write(b"Cool!");
300     ///
301     /// println!("Hash is {:x}!", hasher.finish());
302     /// ```
303     ///
304     /// [`write`]: Hasher::write
305     #[stable(feature = "rust1", since = "1.0.0")]
306     fn finish(&self) -> u64;
307
308     /// Writes some data into this `Hasher`.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// use std::collections::hash_map::DefaultHasher;
314     /// use std::hash::Hasher;
315     ///
316     /// let mut hasher = DefaultHasher::new();
317     /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
318     ///
319     /// hasher.write(&data);
320     ///
321     /// println!("Hash is {:x}!", hasher.finish());
322     /// ```
323     #[stable(feature = "rust1", since = "1.0.0")]
324     fn write(&mut self, bytes: &[u8]);
325
326     /// Writes a single `u8` into this hasher.
327     #[inline]
328     #[stable(feature = "hasher_write", since = "1.3.0")]
329     fn write_u8(&mut self, i: u8) {
330         self.write(&[i])
331     }
332     /// Writes a single `u16` into this hasher.
333     #[inline]
334     #[stable(feature = "hasher_write", since = "1.3.0")]
335     fn write_u16(&mut self, i: u16) {
336         self.write(&i.to_ne_bytes())
337     }
338     /// Writes a single `u32` into this hasher.
339     #[inline]
340     #[stable(feature = "hasher_write", since = "1.3.0")]
341     fn write_u32(&mut self, i: u32) {
342         self.write(&i.to_ne_bytes())
343     }
344     /// Writes a single `u64` into this hasher.
345     #[inline]
346     #[stable(feature = "hasher_write", since = "1.3.0")]
347     fn write_u64(&mut self, i: u64) {
348         self.write(&i.to_ne_bytes())
349     }
350     /// Writes a single `u128` into this hasher.
351     #[inline]
352     #[stable(feature = "i128", since = "1.26.0")]
353     fn write_u128(&mut self, i: u128) {
354         self.write(&i.to_ne_bytes())
355     }
356     /// Writes a single `usize` into this hasher.
357     #[inline]
358     #[stable(feature = "hasher_write", since = "1.3.0")]
359     fn write_usize(&mut self, i: usize) {
360         self.write(&i.to_ne_bytes())
361     }
362
363     /// Writes a single `i8` into this hasher.
364     #[inline]
365     #[stable(feature = "hasher_write", since = "1.3.0")]
366     fn write_i8(&mut self, i: i8) {
367         self.write_u8(i as u8)
368     }
369     /// Writes a single `i16` into this hasher.
370     #[inline]
371     #[stable(feature = "hasher_write", since = "1.3.0")]
372     fn write_i16(&mut self, i: i16) {
373         self.write_u16(i as u16)
374     }
375     /// Writes a single `i32` into this hasher.
376     #[inline]
377     #[stable(feature = "hasher_write", since = "1.3.0")]
378     fn write_i32(&mut self, i: i32) {
379         self.write_u32(i as u32)
380     }
381     /// Writes a single `i64` into this hasher.
382     #[inline]
383     #[stable(feature = "hasher_write", since = "1.3.0")]
384     fn write_i64(&mut self, i: i64) {
385         self.write_u64(i as u64)
386     }
387     /// Writes a single `i128` into this hasher.
388     #[inline]
389     #[stable(feature = "i128", since = "1.26.0")]
390     fn write_i128(&mut self, i: i128) {
391         self.write_u128(i as u128)
392     }
393     /// Writes a single `isize` into this hasher.
394     #[inline]
395     #[stable(feature = "hasher_write", since = "1.3.0")]
396     fn write_isize(&mut self, i: isize) {
397         self.write_usize(i as usize)
398     }
399 }
400
401 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
402 impl<H: Hasher + ?Sized> Hasher for &mut H {
403     fn finish(&self) -> u64 {
404         (**self).finish()
405     }
406     fn write(&mut self, bytes: &[u8]) {
407         (**self).write(bytes)
408     }
409     fn write_u8(&mut self, i: u8) {
410         (**self).write_u8(i)
411     }
412     fn write_u16(&mut self, i: u16) {
413         (**self).write_u16(i)
414     }
415     fn write_u32(&mut self, i: u32) {
416         (**self).write_u32(i)
417     }
418     fn write_u64(&mut self, i: u64) {
419         (**self).write_u64(i)
420     }
421     fn write_u128(&mut self, i: u128) {
422         (**self).write_u128(i)
423     }
424     fn write_usize(&mut self, i: usize) {
425         (**self).write_usize(i)
426     }
427     fn write_i8(&mut self, i: i8) {
428         (**self).write_i8(i)
429     }
430     fn write_i16(&mut self, i: i16) {
431         (**self).write_i16(i)
432     }
433     fn write_i32(&mut self, i: i32) {
434         (**self).write_i32(i)
435     }
436     fn write_i64(&mut self, i: i64) {
437         (**self).write_i64(i)
438     }
439     fn write_i128(&mut self, i: i128) {
440         (**self).write_i128(i)
441     }
442     fn write_isize(&mut self, i: isize) {
443         (**self).write_isize(i)
444     }
445 }
446
447 /// A trait for creating instances of [`Hasher`].
448 ///
449 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
450 /// [`Hasher`]s for each key such that they are hashed independently of one
451 /// another, since [`Hasher`]s contain state.
452 ///
453 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
454 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
455 /// is fed into each hasher, the same output will also be generated.
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// use std::collections::hash_map::RandomState;
461 /// use std::hash::{BuildHasher, Hasher};
462 ///
463 /// let s = RandomState::new();
464 /// let mut hasher_1 = s.build_hasher();
465 /// let mut hasher_2 = s.build_hasher();
466 ///
467 /// hasher_1.write_u32(8128);
468 /// hasher_2.write_u32(8128);
469 ///
470 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
471 /// ```
472 ///
473 /// [`build_hasher`]: BuildHasher::build_hasher
474 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
475 #[stable(since = "1.7.0", feature = "build_hasher")]
476 pub trait BuildHasher {
477     /// Type of the hasher that will be created.
478     #[stable(since = "1.7.0", feature = "build_hasher")]
479     type Hasher: Hasher;
480
481     /// Creates a new hasher.
482     ///
483     /// Each call to `build_hasher` on the same instance should produce identical
484     /// [`Hasher`]s.
485     ///
486     /// # Examples
487     ///
488     /// ```
489     /// use std::collections::hash_map::RandomState;
490     /// use std::hash::BuildHasher;
491     ///
492     /// let s = RandomState::new();
493     /// let new_s = s.build_hasher();
494     /// ```
495     #[stable(since = "1.7.0", feature = "build_hasher")]
496     fn build_hasher(&self) -> Self::Hasher;
497
498     /// Calculates the hash of a single value.
499     ///
500     /// This is intended as a convenience for code which *consumes* hashes, such
501     /// as the implementation of a hash table or in unit tests that check
502     /// whether a custom [`Hash`] implementation behaves as expected.
503     ///
504     /// This must not be used in any code which *creates* hashes, such as in an
505     /// implementation of [`Hash`].  The way to create a combined hash of
506     /// multiple values is to call [`Hash::hash`] multiple times using the same
507     /// [`Hasher`], not to call this method repeatedly and combine the results.
508     ///
509     /// # Example
510     ///
511     /// ```
512     /// #![feature(build_hasher_simple_hash_one)]
513     ///
514     /// use std::cmp::{max, min};
515     /// use std::hash::{BuildHasher, Hash, Hasher};
516     /// struct OrderAmbivalentPair<T: Ord>(T, T);
517     /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
518     ///     fn hash<H: Hasher>(&self, hasher: &mut H) {
519     ///         min(&self.0, &self.1).hash(hasher);
520     ///         max(&self.0, &self.1).hash(hasher);
521     ///     }
522     /// }
523     ///
524     /// // Then later, in a `#[test]` for the type...
525     /// let bh = std::collections::hash_map::RandomState::new();
526     /// assert_eq!(
527     ///     bh.hash_one(OrderAmbivalentPair(1, 2)),
528     ///     bh.hash_one(OrderAmbivalentPair(2, 1))
529     /// );
530     /// assert_eq!(
531     ///     bh.hash_one(OrderAmbivalentPair(10, 2)),
532     ///     bh.hash_one(&OrderAmbivalentPair(2, 10))
533     /// );
534     /// ```
535     #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
536     fn hash_one<T: Hash>(&self, x: T) -> u64
537     where
538         Self: Sized,
539     {
540         let mut hasher = self.build_hasher();
541         x.hash(&mut hasher);
542         hasher.finish()
543     }
544 }
545
546 /// Used to create a default [`BuildHasher`] instance for types that implement
547 /// [`Hasher`] and [`Default`].
548 ///
549 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
550 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
551 /// defined.
552 ///
553 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
554 /// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
555 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
556 /// [`Default`] instances themselves.
557 ///
558 /// # Examples
559 ///
560 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
561 /// [`HashMap`]:
562 ///
563 /// ```
564 /// use std::collections::HashMap;
565 /// use std::hash::{BuildHasherDefault, Hasher};
566 ///
567 /// #[derive(Default)]
568 /// struct MyHasher;
569 ///
570 /// impl Hasher for MyHasher {
571 ///     fn write(&mut self, bytes: &[u8]) {
572 ///         // Your hashing algorithm goes here!
573 ///        unimplemented!()
574 ///     }
575 ///
576 ///     fn finish(&self) -> u64 {
577 ///         // Your hashing algorithm goes here!
578 ///         unimplemented!()
579 ///     }
580 /// }
581 ///
582 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
583 ///
584 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
585 /// ```
586 ///
587 /// [method.default]: BuildHasherDefault::default
588 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
589 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
590 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
591 #[stable(since = "1.7.0", feature = "build_hasher")]
592 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
593
594 #[stable(since = "1.9.0", feature = "core_impl_debug")]
595 impl<H> fmt::Debug for BuildHasherDefault<H> {
596     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
597         f.debug_struct("BuildHasherDefault").finish()
598     }
599 }
600
601 #[stable(since = "1.7.0", feature = "build_hasher")]
602 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
603     type Hasher = H;
604
605     fn build_hasher(&self) -> H {
606         H::default()
607     }
608 }
609
610 #[stable(since = "1.7.0", feature = "build_hasher")]
611 impl<H> Clone for BuildHasherDefault<H> {
612     fn clone(&self) -> BuildHasherDefault<H> {
613         BuildHasherDefault(marker::PhantomData)
614     }
615 }
616
617 #[stable(since = "1.7.0", feature = "build_hasher")]
618 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
619 impl<H> const Default for BuildHasherDefault<H> {
620     fn default() -> BuildHasherDefault<H> {
621         BuildHasherDefault(marker::PhantomData)
622     }
623 }
624
625 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
626 impl<H> PartialEq for BuildHasherDefault<H> {
627     fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
628         true
629     }
630 }
631
632 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
633 impl<H> Eq for BuildHasherDefault<H> {}
634
635 mod impls {
636     use crate::mem;
637     use crate::slice;
638
639     use super::*;
640
641     macro_rules! impl_write {
642         ($(($ty:ident, $meth:ident),)*) => {$(
643             #[stable(feature = "rust1", since = "1.0.0")]
644             impl Hash for $ty {
645                 #[inline]
646                 fn hash<H: Hasher>(&self, state: &mut H) {
647                     state.$meth(*self)
648                 }
649
650                 #[inline]
651                 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
652                     let newlen = data.len() * mem::size_of::<$ty>();
653                     let ptr = data.as_ptr() as *const u8;
654                     // SAFETY: `ptr` is valid and aligned, as this macro is only used
655                     // for numeric primitives which have no padding. The new slice only
656                     // spans across `data` and is never mutated, and its total size is the
657                     // same as the original `data` so it can't be over `isize::MAX`.
658                     state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
659                 }
660             }
661         )*}
662     }
663
664     impl_write! {
665         (u8, write_u8),
666         (u16, write_u16),
667         (u32, write_u32),
668         (u64, write_u64),
669         (usize, write_usize),
670         (i8, write_i8),
671         (i16, write_i16),
672         (i32, write_i32),
673         (i64, write_i64),
674         (isize, write_isize),
675         (u128, write_u128),
676         (i128, write_i128),
677     }
678
679     #[stable(feature = "rust1", since = "1.0.0")]
680     impl Hash for bool {
681         #[inline]
682         fn hash<H: Hasher>(&self, state: &mut H) {
683             state.write_u8(*self as u8)
684         }
685     }
686
687     #[stable(feature = "rust1", since = "1.0.0")]
688     impl Hash for char {
689         #[inline]
690         fn hash<H: Hasher>(&self, state: &mut H) {
691             state.write_u32(*self as u32)
692         }
693     }
694
695     #[stable(feature = "rust1", since = "1.0.0")]
696     impl Hash for str {
697         #[inline]
698         fn hash<H: Hasher>(&self, state: &mut H) {
699             state.write(self.as_bytes());
700             state.write_u8(0xff)
701         }
702     }
703
704     #[stable(feature = "never_hash", since = "1.29.0")]
705     impl Hash for ! {
706         #[inline]
707         fn hash<H: Hasher>(&self, _: &mut H) {
708             *self
709         }
710     }
711
712     macro_rules! impl_hash_tuple {
713         () => (
714             #[stable(feature = "rust1", since = "1.0.0")]
715             impl Hash for () {
716                 #[inline]
717                 fn hash<H: Hasher>(&self, _state: &mut H) {}
718             }
719         );
720
721         ( $($name:ident)+) => (
722             #[stable(feature = "rust1", since = "1.0.0")]
723             impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
724                 #[allow(non_snake_case)]
725                 #[inline]
726                 fn hash<S: Hasher>(&self, state: &mut S) {
727                     let ($(ref $name,)+) = *self;
728                     $($name.hash(state);)+
729                 }
730             }
731         );
732     }
733
734     macro_rules! last_type {
735         ($a:ident,) => { $a };
736         ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
737     }
738
739     impl_hash_tuple! {}
740     impl_hash_tuple! { A }
741     impl_hash_tuple! { A B }
742     impl_hash_tuple! { A B C }
743     impl_hash_tuple! { A B C D }
744     impl_hash_tuple! { A B C D E }
745     impl_hash_tuple! { A B C D E F }
746     impl_hash_tuple! { A B C D E F G }
747     impl_hash_tuple! { A B C D E F G H }
748     impl_hash_tuple! { A B C D E F G H I }
749     impl_hash_tuple! { A B C D E F G H I J }
750     impl_hash_tuple! { A B C D E F G H I J K }
751     impl_hash_tuple! { A B C D E F G H I J K L }
752
753     #[stable(feature = "rust1", since = "1.0.0")]
754     impl<T: Hash> Hash for [T] {
755         #[inline]
756         fn hash<H: Hasher>(&self, state: &mut H) {
757             self.len().hash(state);
758             Hash::hash_slice(self, state)
759         }
760     }
761
762     #[stable(feature = "rust1", since = "1.0.0")]
763     impl<T: ?Sized + Hash> Hash for &T {
764         #[inline]
765         fn hash<H: Hasher>(&self, state: &mut H) {
766             (**self).hash(state);
767         }
768     }
769
770     #[stable(feature = "rust1", since = "1.0.0")]
771     impl<T: ?Sized + Hash> Hash for &mut T {
772         #[inline]
773         fn hash<H: Hasher>(&self, state: &mut H) {
774             (**self).hash(state);
775         }
776     }
777
778     #[stable(feature = "rust1", since = "1.0.0")]
779     impl<T: ?Sized> Hash for *const T {
780         #[inline]
781         fn hash<H: Hasher>(&self, state: &mut H) {
782             let (address, metadata) = self.to_raw_parts();
783             state.write_usize(address as usize);
784             metadata.hash(state);
785         }
786     }
787
788     #[stable(feature = "rust1", since = "1.0.0")]
789     impl<T: ?Sized> Hash for *mut T {
790         #[inline]
791         fn hash<H: Hasher>(&self, state: &mut H) {
792             let (address, metadata) = self.to_raw_parts();
793             state.write_usize(address as usize);
794             metadata.hash(state);
795         }
796     }
797 }