]> git.lizzy.rs Git - rust.git/blob - library/core/src/hash/mod.rs
Auto merge of #95454 - randomicon00:fix95444, r=wesleywiser
[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     ///
337     /// # Note to Implementers
338     ///
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]);
344
345     /// Writes a single `u8` into this hasher.
346     #[inline]
347     #[stable(feature = "hasher_write", since = "1.3.0")]
348     fn write_u8(&mut self, i: u8) {
349         self.write(&[i])
350     }
351     /// Writes a single `u16` into this hasher.
352     #[inline]
353     #[stable(feature = "hasher_write", since = "1.3.0")]
354     fn write_u16(&mut self, i: u16) {
355         self.write(&i.to_ne_bytes())
356     }
357     /// Writes a single `u32` into this hasher.
358     #[inline]
359     #[stable(feature = "hasher_write", since = "1.3.0")]
360     fn write_u32(&mut self, i: u32) {
361         self.write(&i.to_ne_bytes())
362     }
363     /// Writes a single `u64` into this hasher.
364     #[inline]
365     #[stable(feature = "hasher_write", since = "1.3.0")]
366     fn write_u64(&mut self, i: u64) {
367         self.write(&i.to_ne_bytes())
368     }
369     /// Writes a single `u128` into this hasher.
370     #[inline]
371     #[stable(feature = "i128", since = "1.26.0")]
372     fn write_u128(&mut self, i: u128) {
373         self.write(&i.to_ne_bytes())
374     }
375     /// Writes a single `usize` into this hasher.
376     #[inline]
377     #[stable(feature = "hasher_write", since = "1.3.0")]
378     fn write_usize(&mut self, i: usize) {
379         self.write(&i.to_ne_bytes())
380     }
381
382     /// Writes a single `i8` into this hasher.
383     #[inline]
384     #[stable(feature = "hasher_write", since = "1.3.0")]
385     fn write_i8(&mut self, i: i8) {
386         self.write_u8(i as u8)
387     }
388     /// Writes a single `i16` into this hasher.
389     #[inline]
390     #[stable(feature = "hasher_write", since = "1.3.0")]
391     fn write_i16(&mut self, i: i16) {
392         self.write_u16(i as u16)
393     }
394     /// Writes a single `i32` into this hasher.
395     #[inline]
396     #[stable(feature = "hasher_write", since = "1.3.0")]
397     fn write_i32(&mut self, i: i32) {
398         self.write_u32(i as u32)
399     }
400     /// Writes a single `i64` into this hasher.
401     #[inline]
402     #[stable(feature = "hasher_write", since = "1.3.0")]
403     fn write_i64(&mut self, i: i64) {
404         self.write_u64(i as u64)
405     }
406     /// Writes a single `i128` into this hasher.
407     #[inline]
408     #[stable(feature = "i128", since = "1.26.0")]
409     fn write_i128(&mut self, i: i128) {
410         self.write_u128(i as u128)
411     }
412     /// Writes a single `isize` into this hasher.
413     #[inline]
414     #[stable(feature = "hasher_write", since = "1.3.0")]
415     fn write_isize(&mut self, i: isize) {
416         self.write_usize(i as usize)
417     }
418
419     /// Writes a length prefix into this hasher, as part of being prefix-free.
420     ///
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`
426     ///
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.
430     ///
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.
434     ///
435     /// # Examples
436     ///
437     /// ```
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!() }
443     /// # }
444     /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
445     /// #     type Item = T;
446     /// #     type IntoIter = std::iter::Empty<T>;
447     /// #     fn into_iter(self) -> Self::IntoIter { todo!() }
448     /// # }
449     ///
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 {
455     ///             elt.hash(state);
456     ///         }
457     ///     }
458     /// }
459     /// ```
460     ///
461     /// # Note to Implementers
462     ///
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.
466     #[inline]
467     #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
468     fn write_length_prefix(&mut self, len: usize) {
469         self.write_usize(len);
470     }
471
472     /// Writes a single `str` into this hasher.
473     ///
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.
476     ///
477     /// This includes the domain separator for prefix-freedom, so you should
478     /// **not** call `Self::write_length_prefix` before calling this.
479     ///
480     /// # Note to Implementers
481     ///
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.
485     ///
486     /// ## The general answer
487     ///
488     /// It's always correct to implement this with a length prefix:
489     ///
490     /// ```
491     /// # #![feature(hasher_prefixfree_extras)]
492     /// # struct Foo;
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());
499     /// }
500     /// # }
501     /// ```
502     ///
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.
506     ///
507     /// ## If your `Hasher` works byte-wise
508     ///
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:
512     ///
513     /// ```
514     /// # #![feature(hasher_prefixfree_extras)]
515     /// # struct Foo;
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);
522     /// }
523     /// # }
524     /// ```
525     ///
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).
529     ///
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.
533     #[inline]
534     #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
535     fn write_str(&mut self, s: &str) {
536         self.write(s.as_bytes());
537         self.write_u8(0xff);
538     }
539 }
540
541 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
542 impl<H: Hasher + ?Sized> Hasher for &mut H {
543     fn finish(&self) -> u64 {
544         (**self).finish()
545     }
546     fn write(&mut self, bytes: &[u8]) {
547         (**self).write(bytes)
548     }
549     fn write_u8(&mut self, i: u8) {
550         (**self).write_u8(i)
551     }
552     fn write_u16(&mut self, i: u16) {
553         (**self).write_u16(i)
554     }
555     fn write_u32(&mut self, i: u32) {
556         (**self).write_u32(i)
557     }
558     fn write_u64(&mut self, i: u64) {
559         (**self).write_u64(i)
560     }
561     fn write_u128(&mut self, i: u128) {
562         (**self).write_u128(i)
563     }
564     fn write_usize(&mut self, i: usize) {
565         (**self).write_usize(i)
566     }
567     fn write_i8(&mut self, i: i8) {
568         (**self).write_i8(i)
569     }
570     fn write_i16(&mut self, i: i16) {
571         (**self).write_i16(i)
572     }
573     fn write_i32(&mut self, i: i32) {
574         (**self).write_i32(i)
575     }
576     fn write_i64(&mut self, i: i64) {
577         (**self).write_i64(i)
578     }
579     fn write_i128(&mut self, i: i128) {
580         (**self).write_i128(i)
581     }
582     fn write_isize(&mut self, i: isize) {
583         (**self).write_isize(i)
584     }
585     fn write_length_prefix(&mut self, len: usize) {
586         (**self).write_length_prefix(len)
587     }
588     fn write_str(&mut self, s: &str) {
589         (**self).write_str(s)
590     }
591 }
592
593 /// A trait for creating instances of [`Hasher`].
594 ///
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.
598 ///
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.
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// use std::collections::hash_map::RandomState;
607 /// use std::hash::{BuildHasher, Hasher};
608 ///
609 /// let s = RandomState::new();
610 /// let mut hasher_1 = s.build_hasher();
611 /// let mut hasher_2 = s.build_hasher();
612 ///
613 /// hasher_1.write_u32(8128);
614 /// hasher_2.write_u32(8128);
615 ///
616 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
617 /// ```
618 ///
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")]
625     type Hasher: Hasher;
626
627     /// Creates a new hasher.
628     ///
629     /// Each call to `build_hasher` on the same instance should produce identical
630     /// [`Hasher`]s.
631     ///
632     /// # Examples
633     ///
634     /// ```
635     /// use std::collections::hash_map::RandomState;
636     /// use std::hash::BuildHasher;
637     ///
638     /// let s = RandomState::new();
639     /// let new_s = s.build_hasher();
640     /// ```
641     #[stable(since = "1.7.0", feature = "build_hasher")]
642     fn build_hasher(&self) -> Self::Hasher;
643
644     /// Calculates the hash of a single value.
645     ///
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.
649     ///
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.
654     ///
655     /// # Example
656     ///
657     /// ```
658     /// #![feature(build_hasher_simple_hash_one)]
659     ///
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);
667     ///     }
668     /// }
669     ///
670     /// // Then later, in a `#[test]` for the type...
671     /// let bh = std::collections::hash_map::RandomState::new();
672     /// assert_eq!(
673     ///     bh.hash_one(OrderAmbivalentPair(1, 2)),
674     ///     bh.hash_one(OrderAmbivalentPair(2, 1))
675     /// );
676     /// assert_eq!(
677     ///     bh.hash_one(OrderAmbivalentPair(10, 2)),
678     ///     bh.hash_one(&OrderAmbivalentPair(2, 10))
679     /// );
680     /// ```
681     #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
682     fn hash_one<T: Hash>(&self, x: T) -> u64
683     where
684         Self: Sized,
685     {
686         let mut hasher = self.build_hasher();
687         x.hash(&mut hasher);
688         hasher.finish()
689     }
690 }
691
692 /// Used to create a default [`BuildHasher`] instance for types that implement
693 /// [`Hasher`] and [`Default`].
694 ///
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
697 /// defined.
698 ///
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.
703 ///
704 /// # Examples
705 ///
706 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
707 /// [`HashMap`]:
708 ///
709 /// ```
710 /// use std::collections::HashMap;
711 /// use std::hash::{BuildHasherDefault, Hasher};
712 ///
713 /// #[derive(Default)]
714 /// struct MyHasher;
715 ///
716 /// impl Hasher for MyHasher {
717 ///     fn write(&mut self, bytes: &[u8]) {
718 ///         // Your hashing algorithm goes here!
719 ///        unimplemented!()
720 ///     }
721 ///
722 ///     fn finish(&self) -> u64 {
723 ///         // Your hashing algorithm goes here!
724 ///         unimplemented!()
725 ///     }
726 /// }
727 ///
728 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
729 ///
730 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
731 /// ```
732 ///
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>);
739
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()
744     }
745 }
746
747 #[stable(since = "1.7.0", feature = "build_hasher")]
748 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
749     type Hasher = H;
750
751     fn build_hasher(&self) -> H {
752         H::default()
753     }
754 }
755
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)
760     }
761 }
762
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)
768     }
769 }
770
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 {
774         true
775     }
776 }
777
778 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
779 impl<H> Eq for BuildHasherDefault<H> {}
780
781 mod impls {
782     use crate::mem;
783     use crate::slice;
784
785     use super::*;
786
787     macro_rules! impl_write {
788         ($(($ty:ident, $meth:ident),)*) => {$(
789             #[stable(feature = "rust1", since = "1.0.0")]
790             impl Hash for $ty {
791                 #[inline]
792                 fn hash<H: Hasher>(&self, state: &mut H) {
793                     state.$meth(*self)
794                 }
795
796                 #[inline]
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) })
805                 }
806             }
807         )*}
808     }
809
810     impl_write! {
811         (u8, write_u8),
812         (u16, write_u16),
813         (u32, write_u32),
814         (u64, write_u64),
815         (usize, write_usize),
816         (i8, write_i8),
817         (i16, write_i16),
818         (i32, write_i32),
819         (i64, write_i64),
820         (isize, write_isize),
821         (u128, write_u128),
822         (i128, write_i128),
823     }
824
825     #[stable(feature = "rust1", since = "1.0.0")]
826     impl Hash for bool {
827         #[inline]
828         fn hash<H: Hasher>(&self, state: &mut H) {
829             state.write_u8(*self as u8)
830         }
831     }
832
833     #[stable(feature = "rust1", since = "1.0.0")]
834     impl Hash for char {
835         #[inline]
836         fn hash<H: Hasher>(&self, state: &mut H) {
837             state.write_u32(*self as u32)
838         }
839     }
840
841     #[stable(feature = "rust1", since = "1.0.0")]
842     impl Hash for str {
843         #[inline]
844         fn hash<H: Hasher>(&self, state: &mut H) {
845             state.write_str(self);
846         }
847     }
848
849     #[stable(feature = "never_hash", since = "1.29.0")]
850     impl Hash for ! {
851         #[inline]
852         fn hash<H: Hasher>(&self, _: &mut H) {
853             *self
854         }
855     }
856
857     macro_rules! impl_hash_tuple {
858         () => (
859             #[stable(feature = "rust1", since = "1.0.0")]
860             impl Hash for () {
861                 #[inline]
862                 fn hash<H: Hasher>(&self, _state: &mut H) {}
863             }
864         );
865
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)]
870                 #[inline]
871                 fn hash<S: Hasher>(&self, state: &mut S) {
872                     let ($(ref $name,)+) = *self;
873                     $($name.hash(state);)+
874                 }
875             }
876         );
877     }
878
879     macro_rules! last_type {
880         ($a:ident,) => { $a };
881         ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
882     }
883
884     impl_hash_tuple! {}
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 }
897
898     #[stable(feature = "rust1", since = "1.0.0")]
899     impl<T: Hash> Hash for [T] {
900         #[inline]
901         fn hash<H: Hasher>(&self, state: &mut H) {
902             state.write_length_prefix(self.len());
903             Hash::hash_slice(self, state)
904         }
905     }
906
907     #[stable(feature = "rust1", since = "1.0.0")]
908     impl<T: ?Sized + Hash> Hash for &T {
909         #[inline]
910         fn hash<H: Hasher>(&self, state: &mut H) {
911             (**self).hash(state);
912         }
913     }
914
915     #[stable(feature = "rust1", since = "1.0.0")]
916     impl<T: ?Sized + Hash> Hash for &mut T {
917         #[inline]
918         fn hash<H: Hasher>(&self, state: &mut H) {
919             (**self).hash(state);
920         }
921     }
922
923     #[stable(feature = "rust1", since = "1.0.0")]
924     impl<T: ?Sized> Hash for *const T {
925         #[inline]
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);
930         }
931     }
932
933     #[stable(feature = "rust1", since = "1.0.0")]
934     impl<T: ?Sized> Hash for *mut T {
935         #[inline]
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);
940         }
941     }
942 }