]> git.lizzy.rs Git - rust.git/blob - library/core/src/hash/mod.rs
Rollup merge of #91321 - matthewjasper:constaint-placeholders, 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 /// ## Portability
168 ///
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.
172 ///
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`.
175 ///
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.
179 ///
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"]
186 pub trait Hash {
187     /// Feeds this value into the given [`Hasher`].
188     ///
189     /// # Examples
190     ///
191     /// ```
192     /// use std::collections::hash_map::DefaultHasher;
193     /// use std::hash::{Hash, Hasher};
194     ///
195     /// let mut hasher = DefaultHasher::new();
196     /// 7920.hash(&mut hasher);
197     /// println!("Hash is {:x}!", hasher.finish());
198     /// ```
199     #[stable(feature = "rust1", since = "1.0.0")]
200     fn hash<H: Hasher>(&self, state: &mut H);
201
202     /// Feeds a slice of this type into the given [`Hasher`].
203     ///
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`]
209     /// implementation.
210     ///
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
217     /// be used.
218     ///
219     /// # Examples
220     ///
221     /// ```
222     /// use std::collections::hash_map::DefaultHasher;
223     /// use std::hash::{Hash, Hasher};
224     ///
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());
229     /// ```
230     ///
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)
238     where
239         Self: Sized,
240     {
241         for piece in data {
242             piece.hash(state);
243         }
244     }
245 }
246
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 */
255     }
256 }
257 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
258 #[doc(inline)]
259 pub use macros::Hash;
260
261 /// A trait for hashing an arbitrary stream of bytes.
262 ///
263 /// Instances of `Hasher` usually represent state that is changed while hashing
264 /// data.
265 ///
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.
270 ///
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`].
275 ///
276 /// # Examples
277 ///
278 /// ```
279 /// use std::collections::hash_map::DefaultHasher;
280 /// use std::hash::Hasher;
281 ///
282 /// let mut hasher = DefaultHasher::new();
283 ///
284 /// hasher.write_u32(1989);
285 /// hasher.write_u8(11);
286 /// hasher.write_u8(9);
287 /// hasher.write(b"Huh?");
288 ///
289 /// println!("Hash is {:x}!", hasher.finish());
290 /// ```
291 ///
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")]
297 pub trait Hasher {
298     /// Returns the hash value for the values written so far.
299     ///
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
303     /// a new hasher.
304     ///
305     /// # Examples
306     ///
307     /// ```
308     /// use std::collections::hash_map::DefaultHasher;
309     /// use std::hash::Hasher;
310     ///
311     /// let mut hasher = DefaultHasher::new();
312     /// hasher.write(b"Cool!");
313     ///
314     /// println!("Hash is {:x}!", hasher.finish());
315     /// ```
316     ///
317     /// [`write`]: Hasher::write
318     #[stable(feature = "rust1", since = "1.0.0")]
319     fn finish(&self) -> u64;
320
321     /// Writes some data into this `Hasher`.
322     ///
323     /// # Examples
324     ///
325     /// ```
326     /// use std::collections::hash_map::DefaultHasher;
327     /// use std::hash::Hasher;
328     ///
329     /// let mut hasher = DefaultHasher::new();
330     /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
331     ///
332     /// hasher.write(&data);
333     ///
334     /// println!("Hash is {:x}!", hasher.finish());
335     /// ```
336     #[stable(feature = "rust1", since = "1.0.0")]
337     fn write(&mut self, bytes: &[u8]);
338
339     /// Writes a single `u8` into this hasher.
340     #[inline]
341     #[stable(feature = "hasher_write", since = "1.3.0")]
342     fn write_u8(&mut self, i: u8) {
343         self.write(&[i])
344     }
345     /// Writes a single `u16` into this hasher.
346     #[inline]
347     #[stable(feature = "hasher_write", since = "1.3.0")]
348     fn write_u16(&mut self, i: u16) {
349         self.write(&i.to_ne_bytes())
350     }
351     /// Writes a single `u32` into this hasher.
352     #[inline]
353     #[stable(feature = "hasher_write", since = "1.3.0")]
354     fn write_u32(&mut self, i: u32) {
355         self.write(&i.to_ne_bytes())
356     }
357     /// Writes a single `u64` into this hasher.
358     #[inline]
359     #[stable(feature = "hasher_write", since = "1.3.0")]
360     fn write_u64(&mut self, i: u64) {
361         self.write(&i.to_ne_bytes())
362     }
363     /// Writes a single `u128` into this hasher.
364     #[inline]
365     #[stable(feature = "i128", since = "1.26.0")]
366     fn write_u128(&mut self, i: u128) {
367         self.write(&i.to_ne_bytes())
368     }
369     /// Writes a single `usize` into this hasher.
370     #[inline]
371     #[stable(feature = "hasher_write", since = "1.3.0")]
372     fn write_usize(&mut self, i: usize) {
373         self.write(&i.to_ne_bytes())
374     }
375
376     /// Writes a single `i8` into this hasher.
377     #[inline]
378     #[stable(feature = "hasher_write", since = "1.3.0")]
379     fn write_i8(&mut self, i: i8) {
380         self.write_u8(i as u8)
381     }
382     /// Writes a single `i16` into this hasher.
383     #[inline]
384     #[stable(feature = "hasher_write", since = "1.3.0")]
385     fn write_i16(&mut self, i: i16) {
386         self.write_u16(i as u16)
387     }
388     /// Writes a single `i32` into this hasher.
389     #[inline]
390     #[stable(feature = "hasher_write", since = "1.3.0")]
391     fn write_i32(&mut self, i: i32) {
392         self.write_u32(i as u32)
393     }
394     /// Writes a single `i64` into this hasher.
395     #[inline]
396     #[stable(feature = "hasher_write", since = "1.3.0")]
397     fn write_i64(&mut self, i: i64) {
398         self.write_u64(i as u64)
399     }
400     /// Writes a single `i128` into this hasher.
401     #[inline]
402     #[stable(feature = "i128", since = "1.26.0")]
403     fn write_i128(&mut self, i: i128) {
404         self.write_u128(i as u128)
405     }
406     /// Writes a single `isize` into this hasher.
407     #[inline]
408     #[stable(feature = "hasher_write", since = "1.3.0")]
409     fn write_isize(&mut self, i: isize) {
410         self.write_usize(i as usize)
411     }
412 }
413
414 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
415 impl<H: Hasher + ?Sized> Hasher for &mut H {
416     fn finish(&self) -> u64 {
417         (**self).finish()
418     }
419     fn write(&mut self, bytes: &[u8]) {
420         (**self).write(bytes)
421     }
422     fn write_u8(&mut self, i: u8) {
423         (**self).write_u8(i)
424     }
425     fn write_u16(&mut self, i: u16) {
426         (**self).write_u16(i)
427     }
428     fn write_u32(&mut self, i: u32) {
429         (**self).write_u32(i)
430     }
431     fn write_u64(&mut self, i: u64) {
432         (**self).write_u64(i)
433     }
434     fn write_u128(&mut self, i: u128) {
435         (**self).write_u128(i)
436     }
437     fn write_usize(&mut self, i: usize) {
438         (**self).write_usize(i)
439     }
440     fn write_i8(&mut self, i: i8) {
441         (**self).write_i8(i)
442     }
443     fn write_i16(&mut self, i: i16) {
444         (**self).write_i16(i)
445     }
446     fn write_i32(&mut self, i: i32) {
447         (**self).write_i32(i)
448     }
449     fn write_i64(&mut self, i: i64) {
450         (**self).write_i64(i)
451     }
452     fn write_i128(&mut self, i: i128) {
453         (**self).write_i128(i)
454     }
455     fn write_isize(&mut self, i: isize) {
456         (**self).write_isize(i)
457     }
458 }
459
460 /// A trait for creating instances of [`Hasher`].
461 ///
462 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
463 /// [`Hasher`]s for each key such that they are hashed independently of one
464 /// another, since [`Hasher`]s contain state.
465 ///
466 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
467 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
468 /// is fed into each hasher, the same output will also be generated.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// use std::collections::hash_map::RandomState;
474 /// use std::hash::{BuildHasher, Hasher};
475 ///
476 /// let s = RandomState::new();
477 /// let mut hasher_1 = s.build_hasher();
478 /// let mut hasher_2 = s.build_hasher();
479 ///
480 /// hasher_1.write_u32(8128);
481 /// hasher_2.write_u32(8128);
482 ///
483 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
484 /// ```
485 ///
486 /// [`build_hasher`]: BuildHasher::build_hasher
487 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
488 #[stable(since = "1.7.0", feature = "build_hasher")]
489 pub trait BuildHasher {
490     /// Type of the hasher that will be created.
491     #[stable(since = "1.7.0", feature = "build_hasher")]
492     type Hasher: Hasher;
493
494     /// Creates a new hasher.
495     ///
496     /// Each call to `build_hasher` on the same instance should produce identical
497     /// [`Hasher`]s.
498     ///
499     /// # Examples
500     ///
501     /// ```
502     /// use std::collections::hash_map::RandomState;
503     /// use std::hash::BuildHasher;
504     ///
505     /// let s = RandomState::new();
506     /// let new_s = s.build_hasher();
507     /// ```
508     #[stable(since = "1.7.0", feature = "build_hasher")]
509     fn build_hasher(&self) -> Self::Hasher;
510
511     /// Calculates the hash of a single value.
512     ///
513     /// This is intended as a convenience for code which *consumes* hashes, such
514     /// as the implementation of a hash table or in unit tests that check
515     /// whether a custom [`Hash`] implementation behaves as expected.
516     ///
517     /// This must not be used in any code which *creates* hashes, such as in an
518     /// implementation of [`Hash`].  The way to create a combined hash of
519     /// multiple values is to call [`Hash::hash`] multiple times using the same
520     /// [`Hasher`], not to call this method repeatedly and combine the results.
521     ///
522     /// # Example
523     ///
524     /// ```
525     /// #![feature(build_hasher_simple_hash_one)]
526     ///
527     /// use std::cmp::{max, min};
528     /// use std::hash::{BuildHasher, Hash, Hasher};
529     /// struct OrderAmbivalentPair<T: Ord>(T, T);
530     /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
531     ///     fn hash<H: Hasher>(&self, hasher: &mut H) {
532     ///         min(&self.0, &self.1).hash(hasher);
533     ///         max(&self.0, &self.1).hash(hasher);
534     ///     }
535     /// }
536     ///
537     /// // Then later, in a `#[test]` for the type...
538     /// let bh = std::collections::hash_map::RandomState::new();
539     /// assert_eq!(
540     ///     bh.hash_one(OrderAmbivalentPair(1, 2)),
541     ///     bh.hash_one(OrderAmbivalentPair(2, 1))
542     /// );
543     /// assert_eq!(
544     ///     bh.hash_one(OrderAmbivalentPair(10, 2)),
545     ///     bh.hash_one(&OrderAmbivalentPair(2, 10))
546     /// );
547     /// ```
548     #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
549     fn hash_one<T: Hash>(&self, x: T) -> u64
550     where
551         Self: Sized,
552     {
553         let mut hasher = self.build_hasher();
554         x.hash(&mut hasher);
555         hasher.finish()
556     }
557 }
558
559 /// Used to create a default [`BuildHasher`] instance for types that implement
560 /// [`Hasher`] and [`Default`].
561 ///
562 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
563 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
564 /// defined.
565 ///
566 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
567 /// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
568 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
569 /// [`Default`] instances themselves.
570 ///
571 /// # Examples
572 ///
573 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
574 /// [`HashMap`]:
575 ///
576 /// ```
577 /// use std::collections::HashMap;
578 /// use std::hash::{BuildHasherDefault, Hasher};
579 ///
580 /// #[derive(Default)]
581 /// struct MyHasher;
582 ///
583 /// impl Hasher for MyHasher {
584 ///     fn write(&mut self, bytes: &[u8]) {
585 ///         // Your hashing algorithm goes here!
586 ///        unimplemented!()
587 ///     }
588 ///
589 ///     fn finish(&self) -> u64 {
590 ///         // Your hashing algorithm goes here!
591 ///         unimplemented!()
592 ///     }
593 /// }
594 ///
595 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
596 ///
597 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
598 /// ```
599 ///
600 /// [method.default]: BuildHasherDefault::default
601 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
602 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
603 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
604 #[stable(since = "1.7.0", feature = "build_hasher")]
605 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
606
607 #[stable(since = "1.9.0", feature = "core_impl_debug")]
608 impl<H> fmt::Debug for BuildHasherDefault<H> {
609     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610         f.debug_struct("BuildHasherDefault").finish()
611     }
612 }
613
614 #[stable(since = "1.7.0", feature = "build_hasher")]
615 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
616     type Hasher = H;
617
618     fn build_hasher(&self) -> H {
619         H::default()
620     }
621 }
622
623 #[stable(since = "1.7.0", feature = "build_hasher")]
624 impl<H> Clone for BuildHasherDefault<H> {
625     fn clone(&self) -> BuildHasherDefault<H> {
626         BuildHasherDefault(marker::PhantomData)
627     }
628 }
629
630 #[stable(since = "1.7.0", feature = "build_hasher")]
631 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
632 impl<H> const Default for BuildHasherDefault<H> {
633     fn default() -> BuildHasherDefault<H> {
634         BuildHasherDefault(marker::PhantomData)
635     }
636 }
637
638 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
639 impl<H> PartialEq for BuildHasherDefault<H> {
640     fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
641         true
642     }
643 }
644
645 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
646 impl<H> Eq for BuildHasherDefault<H> {}
647
648 mod impls {
649     use crate::mem;
650     use crate::slice;
651
652     use super::*;
653
654     macro_rules! impl_write {
655         ($(($ty:ident, $meth:ident),)*) => {$(
656             #[stable(feature = "rust1", since = "1.0.0")]
657             impl Hash for $ty {
658                 #[inline]
659                 fn hash<H: Hasher>(&self, state: &mut H) {
660                     state.$meth(*self)
661                 }
662
663                 #[inline]
664                 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
665                     let newlen = data.len() * mem::size_of::<$ty>();
666                     let ptr = data.as_ptr() as *const u8;
667                     // SAFETY: `ptr` is valid and aligned, as this macro is only used
668                     // for numeric primitives which have no padding. The new slice only
669                     // spans across `data` and is never mutated, and its total size is the
670                     // same as the original `data` so it can't be over `isize::MAX`.
671                     state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
672                 }
673             }
674         )*}
675     }
676
677     impl_write! {
678         (u8, write_u8),
679         (u16, write_u16),
680         (u32, write_u32),
681         (u64, write_u64),
682         (usize, write_usize),
683         (i8, write_i8),
684         (i16, write_i16),
685         (i32, write_i32),
686         (i64, write_i64),
687         (isize, write_isize),
688         (u128, write_u128),
689         (i128, write_i128),
690     }
691
692     #[stable(feature = "rust1", since = "1.0.0")]
693     impl Hash for bool {
694         #[inline]
695         fn hash<H: Hasher>(&self, state: &mut H) {
696             state.write_u8(*self as u8)
697         }
698     }
699
700     #[stable(feature = "rust1", since = "1.0.0")]
701     impl Hash for char {
702         #[inline]
703         fn hash<H: Hasher>(&self, state: &mut H) {
704             state.write_u32(*self as u32)
705         }
706     }
707
708     #[stable(feature = "rust1", since = "1.0.0")]
709     impl Hash for str {
710         #[inline]
711         fn hash<H: Hasher>(&self, state: &mut H) {
712             state.write(self.as_bytes());
713             state.write_u8(0xff)
714         }
715     }
716
717     #[stable(feature = "never_hash", since = "1.29.0")]
718     impl Hash for ! {
719         #[inline]
720         fn hash<H: Hasher>(&self, _: &mut H) {
721             *self
722         }
723     }
724
725     macro_rules! impl_hash_tuple {
726         () => (
727             #[stable(feature = "rust1", since = "1.0.0")]
728             impl Hash for () {
729                 #[inline]
730                 fn hash<H: Hasher>(&self, _state: &mut H) {}
731             }
732         );
733
734         ( $($name:ident)+) => (
735             #[stable(feature = "rust1", since = "1.0.0")]
736             impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
737                 #[allow(non_snake_case)]
738                 #[inline]
739                 fn hash<S: Hasher>(&self, state: &mut S) {
740                     let ($(ref $name,)+) = *self;
741                     $($name.hash(state);)+
742                 }
743             }
744         );
745     }
746
747     macro_rules! last_type {
748         ($a:ident,) => { $a };
749         ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
750     }
751
752     impl_hash_tuple! {}
753     impl_hash_tuple! { A }
754     impl_hash_tuple! { A B }
755     impl_hash_tuple! { A B C }
756     impl_hash_tuple! { A B C D }
757     impl_hash_tuple! { A B C D E }
758     impl_hash_tuple! { A B C D E F }
759     impl_hash_tuple! { A B C D E F G }
760     impl_hash_tuple! { A B C D E F G H }
761     impl_hash_tuple! { A B C D E F G H I }
762     impl_hash_tuple! { A B C D E F G H I J }
763     impl_hash_tuple! { A B C D E F G H I J K }
764     impl_hash_tuple! { A B C D E F G H I J K L }
765
766     #[stable(feature = "rust1", since = "1.0.0")]
767     impl<T: Hash> Hash for [T] {
768         #[inline]
769         fn hash<H: Hasher>(&self, state: &mut H) {
770             self.len().hash(state);
771             Hash::hash_slice(self, state)
772         }
773     }
774
775     #[stable(feature = "rust1", since = "1.0.0")]
776     impl<T: ?Sized + Hash> Hash for &T {
777         #[inline]
778         fn hash<H: Hasher>(&self, state: &mut H) {
779             (**self).hash(state);
780         }
781     }
782
783     #[stable(feature = "rust1", since = "1.0.0")]
784     impl<T: ?Sized + Hash> Hash for &mut T {
785         #[inline]
786         fn hash<H: Hasher>(&self, state: &mut H) {
787             (**self).hash(state);
788         }
789     }
790
791     #[stable(feature = "rust1", since = "1.0.0")]
792     impl<T: ?Sized> Hash for *const T {
793         #[inline]
794         fn hash<H: Hasher>(&self, state: &mut H) {
795             let (address, metadata) = self.to_raw_parts();
796             state.write_usize(address as usize);
797             metadata.hash(state);
798         }
799     }
800
801     #[stable(feature = "rust1", since = "1.0.0")]
802     impl<T: ?Sized> Hash for *mut T {
803         #[inline]
804         fn hash<H: Hasher>(&self, state: &mut H) {
805             let (address, metadata) = self.to_raw_parts();
806             state.write_usize(address as usize);
807             metadata.hash(state);
808         }
809     }
810 }