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