core/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::hash::{DefaultHasher, Hash, Hasher};
16//!
17//! #[derive(Hash)]
18//! struct Person {
19//! id: u32,
20//! name: String,
21//! phone: u64,
22//! }
23//!
24//! let person1 = Person {
25//! id: 5,
26//! name: "Janet".to_string(),
27//! phone: 555_666_7777,
28//! };
29//! let person2 = Person {
30//! id: 5,
31//! name: "Bob".to_string(),
32//! phone: 555_666_7777,
33//! };
34//!
35//! assert!(calculate_hash(&person1) != calculate_hash(&person2));
36//!
37//! fn calculate_hash<T: Hash>(t: &T) -> u64 {
38//! let mut s = DefaultHasher::new();
39//! t.hash(&mut s);
40//! s.finish()
41//! }
42//! ```
43//!
44//! If you need more control over how a value is hashed, you need to implement
45//! the [`Hash`] trait:
46//!
47//! ```rust
48//! use std::hash::{DefaultHasher, Hash, Hasher};
49//!
50//! struct Person {
51//! id: u32,
52//! # #[allow(dead_code)]
53//! name: String,
54//! phone: u64,
55//! }
56//!
57//! impl Hash for Person {
58//! fn hash<H: Hasher>(&self, state: &mut H) {
59//! self.id.hash(state);
60//! self.phone.hash(state);
61//! }
62//! }
63//!
64//! let person1 = Person {
65//! id: 5,
66//! name: "Janet".to_string(),
67//! phone: 555_666_7777,
68//! };
69//! let person2 = Person {
70//! id: 5,
71//! name: "Bob".to_string(),
72//! phone: 555_666_7777,
73//! };
74//!
75//! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
76//!
77//! fn calculate_hash<T: Hash>(t: &T) -> u64 {
78//! let mut s = DefaultHasher::new();
79//! t.hash(&mut s);
80//! s.finish()
81//! }
82//! ```
83
84#![stable(feature = "rust1", since = "1.0.0")]
85
86#[cfg(not(feature = "ferrocene_subset"))]
87#[stable(feature = "rust1", since = "1.0.0")]
88#[allow(deprecated)]
89pub use self::sip::SipHasher;
90#[cfg(not(feature = "ferrocene_subset"))]
91#[unstable(feature = "hashmap_internals", issue = "none")]
92#[allow(deprecated)]
93#[doc(hidden)]
94pub use self::sip::SipHasher13;
95#[cfg(not(feature = "ferrocene_subset"))]
96use crate::{fmt, marker};
97
98// Ferrocene addition: imports for certified subset
99#[cfg(feature = "ferrocene_subset")]
100#[rustfmt::skip]
101use crate::marker;
102
103#[cfg(not(feature = "ferrocene_subset"))]
104mod sip;
105
106/// A hashable type.
107///
108/// Types implementing `Hash` are able to be [`hash`]ed with an instance of
109/// [`Hasher`].
110///
111/// ## Implementing `Hash`
112///
113/// You can derive `Hash` with `#[derive(Hash)]` if all fields implement `Hash`.
114/// The resulting hash will be the combination of the values from calling
115/// [`hash`] on each field.
116///
117/// ```
118/// #[derive(Hash)]
119/// struct Rustacean {
120/// name: String,
121/// country: String,
122/// }
123/// ```
124///
125/// If you need more control over how a value is hashed, you can of course
126/// implement the `Hash` trait yourself:
127///
128/// ```
129/// use std::hash::{Hash, Hasher};
130///
131/// struct Person {
132/// id: u32,
133/// name: String,
134/// phone: u64,
135/// }
136///
137/// impl Hash for Person {
138/// fn hash<H: Hasher>(&self, state: &mut H) {
139/// self.id.hash(state);
140/// self.phone.hash(state);
141/// }
142/// }
143/// ```
144///
145/// ## `Hash` and `Eq`
146///
147/// When implementing both `Hash` and [`Eq`], it is important that the following
148/// property holds:
149///
150/// ```text
151/// k1 == k2 -> hash(k1) == hash(k2)
152/// ```
153///
154/// In other words, if two keys are equal, their hashes must also be equal.
155/// [`HashMap`] and [`HashSet`] both rely on this behavior.
156///
157/// Thankfully, you won't need to worry about upholding this property when
158/// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
159///
160/// Violating this property is a logic error. The behavior resulting from a logic error is not
161/// specified, but users of the trait must ensure that such logic errors do *not* result in
162/// undefined behavior. This means that `unsafe` code **must not** rely on the correctness of these
163/// methods.
164///
165/// ## Prefix collisions
166///
167/// Implementations of `hash` should ensure that the data they
168/// pass to the `Hasher` are prefix-free. That is,
169/// values which are not equal should cause two different sequences of values to be written,
170/// and neither of the two sequences should be a prefix of the other.
171///
172/// For example, the standard implementation of [`Hash` for `&str`][impl] passes an extra
173/// `0xFF` byte to the `Hasher` so that the values `("ab", "c")` and `("a",
174/// "bc")` hash differently.
175///
176/// ## Portability
177///
178/// Due to differences in endianness and type sizes, data fed by `Hash` to a `Hasher`
179/// should not be considered portable across platforms. Additionally the data passed by most
180/// standard library types should not be considered stable between compiler versions.
181///
182/// This means tests shouldn't probe hard-coded hash values or data fed to a `Hasher` and
183/// instead should check consistency with `Eq`.
184///
185/// Serialization formats intended to be portable between platforms or compiler versions should
186/// either avoid encoding hashes or only rely on `Hash` and `Hasher` implementations that
187/// provide additional guarantees.
188///
189/// [`HashMap`]: ../../std/collections/struct.HashMap.html
190/// [`HashSet`]: ../../std/collections/struct.HashSet.html
191/// [`hash`]: Hash::hash
192/// [impl]: ../../std/primitive.str.html#impl-Hash-for-str
193#[stable(feature = "rust1", since = "1.0.0")]
194#[rustc_diagnostic_item = "Hash"]
195pub trait Hash: marker::PointeeSized {
196 /// Feeds this value into the given [`Hasher`].
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// use std::hash::{DefaultHasher, Hash, Hasher};
202 ///
203 /// let mut hasher = DefaultHasher::new();
204 /// 7920.hash(&mut hasher);
205 /// println!("Hash is {:x}!", hasher.finish());
206 /// ```
207 #[stable(feature = "rust1", since = "1.0.0")]
208 fn hash<H: Hasher>(&self, state: &mut H);
209
210 /// Feeds a slice of this type into the given [`Hasher`].
211 ///
212 /// This method is meant as a convenience, but its implementation is
213 /// also explicitly left unspecified. It isn't guaranteed to be
214 /// equivalent to repeated calls of [`hash`] and implementations of
215 /// [`Hash`] should keep that in mind and call [`hash`] themselves
216 /// if the slice isn't treated as a whole unit in the [`PartialEq`]
217 /// implementation.
218 ///
219 /// For example, a [`VecDeque`] implementation might naïvely call
220 /// [`as_slices`] and then [`hash_slice`] on each slice, but this
221 /// is wrong since the two slices can change with a call to
222 /// [`make_contiguous`] without affecting the [`PartialEq`]
223 /// result. Since these slices aren't treated as singular
224 /// units, and instead part of a larger deque, this method cannot
225 /// be used.
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// use std::hash::{DefaultHasher, Hash, Hasher};
231 ///
232 /// let mut hasher = DefaultHasher::new();
233 /// let numbers = [6, 28, 496, 8128];
234 /// Hash::hash_slice(&numbers, &mut hasher);
235 /// println!("Hash is {:x}!", hasher.finish());
236 /// ```
237 ///
238 /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html
239 /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices
240 /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous
241 /// [`hash`]: Hash::hash
242 /// [`hash_slice`]: Hash::hash_slice
243 #[stable(feature = "hash_slice", since = "1.3.0")]
244 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
245 where
246 Self: Sized,
247 {
248 for piece in data {
249 piece.hash(state)
250 }
251 }
252}
253
254// Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
255pub(crate) mod macros {
256 /// Derive macro generating an impl of the trait `Hash`.
257 #[rustc_builtin_macro]
258 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
259 #[allow_internal_unstable(core_intrinsics)]
260 pub macro Hash($item:item) {
261 /* compiler built-in */
262 }
263}
264#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
265#[doc(inline)]
266pub use macros::Hash;
267
268/// A trait for hashing an arbitrary stream of bytes.
269///
270/// Instances of `Hasher` usually represent state that is changed while hashing
271/// data.
272///
273/// `Hasher` provides a fairly basic interface for retrieving the generated hash
274/// (with [`finish`]), and writing integers as well as slices of bytes into an
275/// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
276/// instances are used in conjunction with the [`Hash`] trait.
277///
278/// This trait provides no guarantees about how the various `write_*` methods are
279/// defined and implementations of [`Hash`] should not assume that they work one
280/// way or another. You cannot assume, for example, that a [`write_u32`] call is
281/// equivalent to four calls of [`write_u8`]. Nor can you assume that adjacent
282/// `write` calls are merged, so it's possible, for example, that
283/// ```
284/// # fn foo(hasher: &mut impl std::hash::Hasher) {
285/// hasher.write(&[1, 2]);
286/// hasher.write(&[3, 4, 5, 6]);
287/// # }
288/// ```
289/// and
290/// ```
291/// # fn foo(hasher: &mut impl std::hash::Hasher) {
292/// hasher.write(&[1, 2, 3, 4]);
293/// hasher.write(&[5, 6]);
294/// # }
295/// ```
296/// end up producing different hashes.
297///
298/// Thus to produce the same hash value, [`Hash`] implementations must ensure
299/// for equivalent items that exactly the same sequence of calls is made -- the
300/// same methods with the same parameters in the same order.
301///
302/// # Examples
303///
304/// ```
305/// use std::hash::{DefaultHasher, Hasher};
306///
307/// let mut hasher = DefaultHasher::new();
308///
309/// hasher.write_u32(1989);
310/// hasher.write_u8(11);
311/// hasher.write_u8(9);
312/// hasher.write(b"Huh?");
313///
314/// println!("Hash is {:x}!", hasher.finish());
315/// ```
316///
317/// [`finish`]: Hasher::finish
318/// [`write`]: Hasher::write
319/// [`write_u8`]: Hasher::write_u8
320/// [`write_u32`]: Hasher::write_u32
321#[stable(feature = "rust1", since = "1.0.0")]
322pub trait Hasher {
323 /// Returns the hash value for the values written so far.
324 ///
325 /// Despite its name, the method does not reset the hasher’s internal
326 /// state. Additional [`write`]s will continue from the current value.
327 /// If you need to start a fresh hash value, you will have to create
328 /// a new hasher.
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// use std::hash::{DefaultHasher, Hasher};
334 ///
335 /// let mut hasher = DefaultHasher::new();
336 /// hasher.write(b"Cool!");
337 ///
338 /// println!("Hash is {:x}!", hasher.finish());
339 /// ```
340 ///
341 /// [`write`]: Hasher::write
342 #[stable(feature = "rust1", since = "1.0.0")]
343 #[must_use]
344 fn finish(&self) -> u64;
345
346 /// Writes some data into this `Hasher`.
347 ///
348 /// # Examples
349 ///
350 /// ```
351 /// use std::hash::{DefaultHasher, Hasher};
352 ///
353 /// let mut hasher = DefaultHasher::new();
354 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
355 ///
356 /// hasher.write(&data);
357 ///
358 /// println!("Hash is {:x}!", hasher.finish());
359 /// ```
360 ///
361 /// # Note to Implementers
362 ///
363 /// You generally should not do length-prefixing as part of implementing
364 /// this method. It's up to the [`Hash`] implementation to call
365 /// [`Hasher::write_length_prefix`] before sequences that need it.
366 #[stable(feature = "rust1", since = "1.0.0")]
367 fn write(&mut self, bytes: &[u8]);
368
369 /// Writes a single `u8` into this hasher.
370 #[inline]
371 #[stable(feature = "hasher_write", since = "1.3.0")]
372 fn write_u8(&mut self, i: u8) {
373 self.write(&[i])
374 }
375 /// Writes a single `u16` into this hasher.
376 #[inline]
377 #[stable(feature = "hasher_write", since = "1.3.0")]
378 fn write_u16(&mut self, i: u16) {
379 self.write(&i.to_ne_bytes())
380 }
381 /// Writes a single `u32` into this hasher.
382 #[inline]
383 #[stable(feature = "hasher_write", since = "1.3.0")]
384 fn write_u32(&mut self, i: u32) {
385 self.write(&i.to_ne_bytes())
386 }
387 /// Writes a single `u64` into this hasher.
388 #[inline]
389 #[stable(feature = "hasher_write", since = "1.3.0")]
390 fn write_u64(&mut self, i: u64) {
391 self.write(&i.to_ne_bytes())
392 }
393 /// Writes a single `u128` into this hasher.
394 #[inline]
395 #[stable(feature = "i128", since = "1.26.0")]
396 fn write_u128(&mut self, i: u128) {
397 self.write(&i.to_ne_bytes())
398 }
399 /// Writes a single `usize` into this hasher.
400 #[inline]
401 #[stable(feature = "hasher_write", since = "1.3.0")]
402 fn write_usize(&mut self, i: usize) {
403 self.write(&i.to_ne_bytes())
404 }
405
406 /// Writes a single `i8` into this hasher.
407 #[inline]
408 #[stable(feature = "hasher_write", since = "1.3.0")]
409 fn write_i8(&mut self, i: i8) {
410 self.write_u8(i as u8)
411 }
412 /// Writes a single `i16` into this hasher.
413 #[inline]
414 #[stable(feature = "hasher_write", since = "1.3.0")]
415 fn write_i16(&mut self, i: i16) {
416 self.write_u16(i as u16)
417 }
418 /// Writes a single `i32` into this hasher.
419 #[inline]
420 #[stable(feature = "hasher_write", since = "1.3.0")]
421 fn write_i32(&mut self, i: i32) {
422 self.write_u32(i as u32)
423 }
424 /// Writes a single `i64` into this hasher.
425 #[inline]
426 #[stable(feature = "hasher_write", since = "1.3.0")]
427 fn write_i64(&mut self, i: i64) {
428 self.write_u64(i as u64)
429 }
430 /// Writes a single `i128` into this hasher.
431 #[inline]
432 #[stable(feature = "i128", since = "1.26.0")]
433 fn write_i128(&mut self, i: i128) {
434 self.write_u128(i as u128)
435 }
436 /// Writes a single `isize` into this hasher.
437 #[inline]
438 #[stable(feature = "hasher_write", since = "1.3.0")]
439 fn write_isize(&mut self, i: isize) {
440 self.write_usize(i as usize)
441 }
442
443 /// Writes a length prefix into this hasher, as part of being prefix-free.
444 ///
445 /// If you're implementing [`Hash`] for a custom collection, call this before
446 /// writing its contents to this `Hasher`. That way
447 /// `(collection![1, 2, 3], collection![4, 5])` and
448 /// `(collection![1, 2], collection![3, 4, 5])` will provide different
449 /// sequences of values to the `Hasher`
450 ///
451 /// The `impl<T> Hash for [T]` includes a call to this method, so if you're
452 /// hashing a slice (or array or vector) via its `Hash::hash` method,
453 /// you should **not** call this yourself.
454 ///
455 /// This method is only for providing domain separation. If you want to
456 /// hash a `usize` that represents part of the *data*, then it's important
457 /// that you pass it to [`Hasher::write_usize`] instead of to this method.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// #![feature(hasher_prefixfree_extras)]
463 /// # // Stubs to make the `impl` below pass the compiler
464 /// # #![allow(non_local_definitions)]
465 /// # struct MyCollection<T>(Option<T>);
466 /// # impl<T> MyCollection<T> {
467 /// # fn len(&self) -> usize { todo!() }
468 /// # }
469 /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
470 /// # type Item = T;
471 /// # type IntoIter = std::iter::Empty<T>;
472 /// # fn into_iter(self) -> Self::IntoIter { todo!() }
473 /// # }
474 ///
475 /// use std::hash::{Hash, Hasher};
476 /// impl<T: Hash> Hash for MyCollection<T> {
477 /// fn hash<H: Hasher>(&self, state: &mut H) {
478 /// state.write_length_prefix(self.len());
479 /// for elt in self {
480 /// elt.hash(state);
481 /// }
482 /// }
483 /// }
484 /// ```
485 ///
486 /// # Note to Implementers
487 ///
488 /// If you've decided that your `Hasher` is willing to be susceptible to
489 /// Hash-DoS attacks, then you might consider skipping hashing some or all
490 /// of the `len` provided in the name of increased performance.
491 #[inline]
492 #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
493 fn write_length_prefix(&mut self, len: usize) {
494 self.write_usize(len);
495 }
496
497 /// Writes a single `str` into this hasher.
498 ///
499 /// If you're implementing [`Hash`], you generally do not need to call this,
500 /// as the `impl Hash for str` does, so you should prefer that instead.
501 ///
502 /// This includes the domain separator for prefix-freedom, so you should
503 /// **not** call `Self::write_length_prefix` before calling this.
504 ///
505 /// # Note to Implementers
506 ///
507 /// There are at least two reasonable default ways to implement this.
508 /// Which one will be the default is not yet decided, so for now
509 /// you probably want to override it specifically.
510 ///
511 /// ## The general answer
512 ///
513 /// It's always correct to implement this with a length prefix:
514 ///
515 /// ```
516 /// # #![feature(hasher_prefixfree_extras)]
517 /// # struct Foo;
518 /// # impl std::hash::Hasher for Foo {
519 /// # fn finish(&self) -> u64 { unimplemented!() }
520 /// # fn write(&mut self, _bytes: &[u8]) { unimplemented!() }
521 /// fn write_str(&mut self, s: &str) {
522 /// self.write_length_prefix(s.len());
523 /// self.write(s.as_bytes());
524 /// }
525 /// # }
526 /// ```
527 ///
528 /// And, if your `Hasher` works in `usize` chunks, this is likely a very
529 /// efficient way to do it, as anything more complicated may well end up
530 /// slower than just running the round with the length.
531 ///
532 /// ## If your `Hasher` works byte-wise
533 ///
534 /// One nice thing about `str` being UTF-8 is that the `b'\xFF'` byte
535 /// never happens. That means that you can append that to the byte stream
536 /// being hashed and maintain prefix-freedom:
537 ///
538 /// ```
539 /// # #![feature(hasher_prefixfree_extras)]
540 /// # struct Foo;
541 /// # impl std::hash::Hasher for Foo {
542 /// # fn finish(&self) -> u64 { unimplemented!() }
543 /// # fn write(&mut self, _bytes: &[u8]) { unimplemented!() }
544 /// fn write_str(&mut self, s: &str) {
545 /// self.write(s.as_bytes());
546 /// self.write_u8(0xff);
547 /// }
548 /// # }
549 /// ```
550 ///
551 /// This does require that your implementation not add extra padding, and
552 /// thus generally requires that you maintain a buffer, running a round
553 /// only once that buffer is full (or `finish` is called).
554 ///
555 /// That's because if `write` pads data out to a fixed chunk size, it's
556 /// likely that it does it in such a way that `"a"` and `"a\x00"` would
557 /// end up hashing the same sequence of things, introducing conflicts.
558 #[inline]
559 #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
560 fn write_str(&mut self, s: &str) {
561 self.write(s.as_bytes());
562 self.write_u8(0xff);
563 }
564}
565
566#[cfg(not(feature = "ferrocene_subset"))]
567#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
568impl<H: Hasher + ?Sized> Hasher for &mut H {
569 fn finish(&self) -> u64 {
570 (**self).finish()
571 }
572 fn write(&mut self, bytes: &[u8]) {
573 (**self).write(bytes)
574 }
575 fn write_u8(&mut self, i: u8) {
576 (**self).write_u8(i)
577 }
578 fn write_u16(&mut self, i: u16) {
579 (**self).write_u16(i)
580 }
581 fn write_u32(&mut self, i: u32) {
582 (**self).write_u32(i)
583 }
584 fn write_u64(&mut self, i: u64) {
585 (**self).write_u64(i)
586 }
587 fn write_u128(&mut self, i: u128) {
588 (**self).write_u128(i)
589 }
590 fn write_usize(&mut self, i: usize) {
591 (**self).write_usize(i)
592 }
593 fn write_i8(&mut self, i: i8) {
594 (**self).write_i8(i)
595 }
596 fn write_i16(&mut self, i: i16) {
597 (**self).write_i16(i)
598 }
599 fn write_i32(&mut self, i: i32) {
600 (**self).write_i32(i)
601 }
602 fn write_i64(&mut self, i: i64) {
603 (**self).write_i64(i)
604 }
605 fn write_i128(&mut self, i: i128) {
606 (**self).write_i128(i)
607 }
608 fn write_isize(&mut self, i: isize) {
609 (**self).write_isize(i)
610 }
611 fn write_length_prefix(&mut self, len: usize) {
612 (**self).write_length_prefix(len)
613 }
614 fn write_str(&mut self, s: &str) {
615 (**self).write_str(s)
616 }
617}
618
619/// A trait for creating instances of [`Hasher`].
620///
621/// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
622/// [`Hasher`]s for each key such that they are hashed independently of one
623/// another, since [`Hasher`]s contain state.
624///
625/// For each instance of `BuildHasher`, the [`Hasher`]s created by
626/// [`build_hasher`] should be identical. That is, if the same stream of bytes
627/// is fed into each hasher, the same output will also be generated.
628///
629/// # Examples
630///
631/// ```
632/// use std::hash::{BuildHasher, Hasher, RandomState};
633///
634/// let s = RandomState::new();
635/// let mut hasher_1 = s.build_hasher();
636/// let mut hasher_2 = s.build_hasher();
637///
638/// hasher_1.write_u32(8128);
639/// hasher_2.write_u32(8128);
640///
641/// assert_eq!(hasher_1.finish(), hasher_2.finish());
642/// ```
643///
644/// [`build_hasher`]: BuildHasher::build_hasher
645/// [`HashMap`]: ../../std/collections/struct.HashMap.html
646#[cfg(not(feature = "ferrocene_subset"))]
647#[cfg_attr(not(test), rustc_diagnostic_item = "BuildHasher")]
648#[stable(since = "1.7.0", feature = "build_hasher")]
649pub trait BuildHasher {
650 /// Type of the hasher that will be created.
651 #[stable(since = "1.7.0", feature = "build_hasher")]
652 type Hasher: Hasher;
653
654 /// Creates a new hasher.
655 ///
656 /// Each call to `build_hasher` on the same instance should produce identical
657 /// [`Hasher`]s.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// use std::hash::{BuildHasher, RandomState};
663 ///
664 /// let s = RandomState::new();
665 /// let new_s = s.build_hasher();
666 /// ```
667 #[stable(since = "1.7.0", feature = "build_hasher")]
668 fn build_hasher(&self) -> Self::Hasher;
669
670 /// Calculates the hash of a single value.
671 ///
672 /// This is intended as a convenience for code which *consumes* hashes, such
673 /// as the implementation of a hash table or in unit tests that check
674 /// whether a custom [`Hash`] implementation behaves as expected.
675 ///
676 /// This must not be used in any code which *creates* hashes, such as in an
677 /// implementation of [`Hash`]. The way to create a combined hash of
678 /// multiple values is to call [`Hash::hash`] multiple times using the same
679 /// [`Hasher`], not to call this method repeatedly and combine the results.
680 ///
681 /// # Example
682 ///
683 /// ```
684 /// use std::cmp::{max, min};
685 /// use std::hash::{BuildHasher, Hash, Hasher};
686 /// struct OrderAmbivalentPair<T: Ord>(T, T);
687 /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
688 /// fn hash<H: Hasher>(&self, hasher: &mut H) {
689 /// min(&self.0, &self.1).hash(hasher);
690 /// max(&self.0, &self.1).hash(hasher);
691 /// }
692 /// }
693 ///
694 /// // Then later, in a `#[test]` for the type...
695 /// let bh = std::hash::RandomState::new();
696 /// assert_eq!(
697 /// bh.hash_one(OrderAmbivalentPair(1, 2)),
698 /// bh.hash_one(OrderAmbivalentPair(2, 1))
699 /// );
700 /// assert_eq!(
701 /// bh.hash_one(OrderAmbivalentPair(10, 2)),
702 /// bh.hash_one(&OrderAmbivalentPair(2, 10))
703 /// );
704 /// ```
705 #[stable(feature = "build_hasher_simple_hash_one", since = "1.71.0")]
706 fn hash_one<T: Hash>(&self, x: T) -> u64
707 where
708 Self: Sized,
709 Self::Hasher: Hasher,
710 {
711 let mut hasher = self.build_hasher();
712 x.hash(&mut hasher);
713 hasher.finish()
714 }
715}
716
717/// Used to create a default [`BuildHasher`] instance for types that implement
718/// [`Hasher`] and [`Default`].
719///
720/// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
721/// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
722/// defined.
723///
724/// Any `BuildHasherDefault` is [zero-sized]. It can be created with
725/// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
726/// [`HashSet`], this doesn't need to be done, since they implement appropriate
727/// [`Default`] instances themselves.
728///
729/// # Examples
730///
731/// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
732/// [`HashMap`]:
733///
734/// ```
735/// use std::collections::HashMap;
736/// use std::hash::{BuildHasherDefault, Hasher};
737///
738/// #[derive(Default)]
739/// struct MyHasher;
740///
741/// impl Hasher for MyHasher {
742/// fn write(&mut self, bytes: &[u8]) {
743/// // Your hashing algorithm goes here!
744/// unimplemented!()
745/// }
746///
747/// fn finish(&self) -> u64 {
748/// // Your hashing algorithm goes here!
749/// unimplemented!()
750/// }
751/// }
752///
753/// type MyBuildHasher = BuildHasherDefault<MyHasher>;
754///
755/// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
756/// ```
757///
758/// [method.default]: BuildHasherDefault::default
759/// [`HashMap`]: ../../std/collections/struct.HashMap.html
760/// [`HashSet`]: ../../std/collections/struct.HashSet.html
761/// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
762#[cfg(not(feature = "ferrocene_subset"))]
763#[stable(since = "1.7.0", feature = "build_hasher")]
764pub struct BuildHasherDefault<H>(marker::PhantomData<fn() -> H>);
765
766#[cfg(not(feature = "ferrocene_subset"))]
767impl<H> BuildHasherDefault<H> {
768 /// Creates a new BuildHasherDefault for Hasher `H`.
769 #[stable(feature = "build_hasher_default_const_new", since = "1.85.0")]
770 #[rustc_const_stable(feature = "build_hasher_default_const_new", since = "1.85.0")]
771 pub const fn new() -> Self {
772 BuildHasherDefault(marker::PhantomData)
773 }
774}
775
776#[cfg(not(feature = "ferrocene_subset"))]
777#[stable(since = "1.9.0", feature = "core_impl_debug")]
778impl<H> fmt::Debug for BuildHasherDefault<H> {
779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
780 f.debug_struct("BuildHasherDefault").finish()
781 }
782}
783
784#[cfg(not(feature = "ferrocene_subset"))]
785#[stable(since = "1.7.0", feature = "build_hasher")]
786impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
787 type Hasher = H;
788
789 fn build_hasher(&self) -> H {
790 H::default()
791 }
792}
793
794#[cfg(not(feature = "ferrocene_subset"))]
795#[stable(since = "1.7.0", feature = "build_hasher")]
796impl<H> Clone for BuildHasherDefault<H> {
797 fn clone(&self) -> BuildHasherDefault<H> {
798 BuildHasherDefault(marker::PhantomData)
799 }
800}
801
802#[cfg(not(feature = "ferrocene_subset"))]
803#[stable(since = "1.7.0", feature = "build_hasher")]
804impl<H> Default for BuildHasherDefault<H> {
805 fn default() -> BuildHasherDefault<H> {
806 Self::new()
807 }
808}
809
810#[cfg(not(feature = "ferrocene_subset"))]
811#[stable(since = "1.29.0", feature = "build_hasher_eq")]
812impl<H> PartialEq for BuildHasherDefault<H> {
813 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
814 true
815 }
816}
817
818#[cfg(not(feature = "ferrocene_subset"))]
819#[stable(since = "1.29.0", feature = "build_hasher_eq")]
820impl<H> Eq for BuildHasherDefault<H> {}
821
822mod impls {
823 use super::*;
824 use crate::slice;
825
826 macro_rules! impl_write {
827 ($(($ty:ident, $meth:ident),)*) => {$(
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl Hash for $ty {
830 #[inline]
831 fn hash<H: Hasher>(&self, state: &mut H) {
832 state.$meth(*self)
833 }
834
835 #[inline]
836 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
837 let newlen = size_of_val(data);
838 let ptr = data.as_ptr() as *const u8;
839 // SAFETY: `ptr` is valid and aligned, as this macro is only used
840 // for numeric primitives which have no padding. The new slice only
841 // spans across `data` and is never mutated, and its total size is the
842 // same as the original `data` so it can't be over `isize::MAX`.
843 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
844 }
845 }
846 )*}
847 }
848
849 impl_write! {
850 (u8, write_u8),
851 (u16, write_u16),
852 (u32, write_u32),
853 (u64, write_u64),
854 (usize, write_usize),
855 (i8, write_i8),
856 (i16, write_i16),
857 (i32, write_i32),
858 (i64, write_i64),
859 (isize, write_isize),
860 (u128, write_u128),
861 (i128, write_i128),
862 }
863
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl Hash for bool {
866 #[inline]
867 fn hash<H: Hasher>(&self, state: &mut H) {
868 state.write_u8(*self as u8)
869 }
870 }
871
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl Hash for char {
874 #[inline]
875 fn hash<H: Hasher>(&self, state: &mut H) {
876 state.write_u32(*self as u32)
877 }
878 }
879
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl Hash for str {
882 #[inline]
883 fn hash<H: Hasher>(&self, state: &mut H) {
884 state.write_str(self);
885 }
886 }
887
888 #[stable(feature = "never_hash", since = "1.29.0")]
889 impl Hash for ! {
890 #[inline]
891 fn hash<H: Hasher>(&self, _: &mut H) {
892 *self
893 }
894 }
895
896 macro_rules! impl_hash_tuple {
897 () => (
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl Hash for () {
900 #[inline]
901 fn hash<H: Hasher>(&self, _state: &mut H) {}
902 }
903 );
904
905 ( $($name:ident)+) => (
906 maybe_tuple_doc! {
907 $($name)+ @
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<$($name: Hash),+> Hash for ($($name,)+) {
910 #[allow(non_snake_case)]
911 #[inline]
912 fn hash<S: Hasher>(&self, state: &mut S) {
913 let ($(ref $name,)+) = *self;
914 $($name.hash(state);)+
915 }
916 }
917 }
918 );
919 }
920
921 macro_rules! maybe_tuple_doc {
922 ($a:ident @ #[$meta:meta] $item:item) => {
923 #[doc(fake_variadic)]
924 #[doc = "This trait is implemented for tuples up to twelve items long."]
925 #[$meta]
926 $item
927 };
928 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
929 #[doc(hidden)]
930 #[$meta]
931 $item
932 };
933 }
934
935 impl_hash_tuple! {}
936 impl_hash_tuple! { T }
937 impl_hash_tuple! { T B }
938 impl_hash_tuple! { T B C }
939 impl_hash_tuple! { T B C D }
940 impl_hash_tuple! { T B C D E }
941 impl_hash_tuple! { T B C D E F }
942 impl_hash_tuple! { T B C D E F G }
943 impl_hash_tuple! { T B C D E F G H }
944 impl_hash_tuple! { T B C D E F G H I }
945 impl_hash_tuple! { T B C D E F G H I J }
946 impl_hash_tuple! { T B C D E F G H I J K }
947 impl_hash_tuple! { T B C D E F G H I J K L }
948
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<T: Hash> Hash for [T] {
951 #[inline]
952 fn hash<H: Hasher>(&self, state: &mut H) {
953 state.write_length_prefix(self.len());
954 Hash::hash_slice(self, state)
955 }
956 }
957
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl<T: ?Sized + marker::PointeeSized + Hash> Hash for &T {
960 #[inline]
961 fn hash<H: Hasher>(&self, state: &mut H) {
962 (**self).hash(state);
963 }
964 }
965
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<T: ?Sized + marker::PointeeSized + Hash> Hash for &mut T {
968 #[inline]
969 fn hash<H: Hasher>(&self, state: &mut H) {
970 (**self).hash(state);
971 }
972 }
973
974 #[stable(feature = "rust1", since = "1.0.0")]
975 impl<T: ?Sized + marker::PointeeSized> Hash for *const T {
976 #[inline]
977 fn hash<H: Hasher>(&self, state: &mut H) {
978 let (address, metadata) = self.to_raw_parts();
979 state.write_usize(address.addr());
980 metadata.hash(state);
981 }
982 }
983
984 #[stable(feature = "rust1", since = "1.0.0")]
985 impl<T: ?Sized + marker::PointeeSized> Hash for *mut T {
986 #[inline]
987 fn hash<H: Hasher>(&self, state: &mut H) {
988 let (address, metadata) = self.to_raw_parts();
989 state.write_usize(address.addr());
990 metadata.hash(state);
991 }
992 }
993}