]> git.proxmox.com Git - rustc.git/blame - library/core/src/hash/mod.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / library / core / src / hash / mod.rs
CommitLineData
1a4d82fc
JJ
1//! Generic hashing support.
2//!
6a06907d
XL
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)]`:
1a4d82fc
JJ
11//!
12//! # Examples
13//!
14//! ```rust
cc61c64b
XL
15//! use std::collections::hash_map::DefaultHasher;
16//! use std::hash::{Hash, Hasher};
1a4d82fc
JJ
17//!
18//! #[derive(Hash)]
19//! struct Person {
c34b1796 20//! id: u32,
1a4d82fc
JJ
21//! name: String,
22//! phone: u64,
23//! }
24//!
cc61c64b
XL
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//! };
1a4d82fc 35//!
cc61c64b 36//! assert!(calculate_hash(&person1) != calculate_hash(&person2));
e9174d1e 37//!
cc61c64b
XL
38//! fn calculate_hash<T: Hash>(t: &T) -> u64 {
39//! let mut s = DefaultHasher::new();
e9174d1e
SL
40//! t.hash(&mut s);
41//! s.finish()
42//! }
1a4d82fc
JJ
43//! ```
44//!
45//! If you need more control over how a value is hashed, you need to implement
c30ab7b3
SL
46//! the [`Hash`] trait:
47//!
1a4d82fc 48//! ```rust
cc61c64b
XL
49//! use std::collections::hash_map::DefaultHasher;
50//! use std::hash::{Hash, Hasher};
1a4d82fc
JJ
51//!
52//! struct Person {
c34b1796 53//! id: u32,
cc61c64b 54//! # #[allow(dead_code)]
1a4d82fc
JJ
55//! name: String,
56//! phone: u64,
57//! }
58//!
85aaf69f
SL
59//! impl Hash for Person {
60//! fn hash<H: Hasher>(&self, state: &mut H) {
1a4d82fc
JJ
61//! self.id.hash(state);
62//! self.phone.hash(state);
63//! }
64//! }
65//!
cc61c64b
XL
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//! };
1a4d82fc 76//!
cc61c64b 77//! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
e9174d1e 78//!
cc61c64b
XL
79//! fn calculate_hash<T: Hash>(t: &T) -> u64 {
80//! let mut s = DefaultHasher::new();
e9174d1e
SL
81//! t.hash(&mut s);
82//! s.finish()
83//! }
1a4d82fc
JJ
84//! ```
85
85aaf69f
SL
86#![stable(feature = "rust1", since = "1.0.0")]
87
48663c56
XL
88use crate::fmt;
89use crate::marker;
1a4d82fc 90
92a42be0 91#[stable(feature = "rust1", since = "1.0.0")]
9e0c209e 92#[allow(deprecated)]
1a4d82fc
JJ
93pub use self::sip::SipHasher;
94
dfeec247 95#[unstable(feature = "hashmap_internals", issue = "none")]
9e0c209e 96#[allow(deprecated)]
0531ce1d
XL
97#[doc(hidden)]
98pub use self::sip::SipHasher13;
3157f602 99
1a4d82fc
JJ
100mod sip;
101
102/// A hashable type.
103///
cc61c64b
XL
104/// Types implementing `Hash` are able to be [`hash`]ed with an instance of
105/// [`Hasher`].
c34b1796 106///
cc61c64b 107/// ## Implementing `Hash`
c34b1796 108///
cc61c64b
XL
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.
92a42be0 112///
cc61c64b
XL
113/// ```
114/// #[derive(Hash)]
115/// struct Rustacean {
116/// name: String,
117/// country: String,
118/// }
119/// ```
3157f602 120///
cc61c64b
XL
121/// If you need more control over how a value is hashed, you can of course
122/// implement the `Hash` trait yourself:
3157f602
XL
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/// ```
c30ab7b3 140///
cc61c64b
XL
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///
c295e0f8
XL
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///
a2a8927a
XL
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///
c30ab7b3
SL
180/// [`HashMap`]: ../../std/collections/struct.HashMap.html
181/// [`HashSet`]: ../../std/collections/struct.HashSet.html
1b1a35ee 182/// [`hash`]: Hash::hash
c295e0f8 183/// [impl]: ../../std/primitive.str.html#impl-Hash
85aaf69f 184#[stable(feature = "rust1", since = "1.0.0")]
c295e0f8 185#[rustc_diagnostic_item = "Hash"]
85aaf69f 186pub trait Hash {
cc61c64b
XL
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 /// ```
85aaf69f
SL
199 #[stable(feature = "rust1", since = "1.0.0")]
200 fn hash<H: Hasher>(&self, state: &mut H);
201
cc61c64b
XL
202 /// Feeds a slice of this type into the given [`Hasher`].
203 ///
cdc7bbd5
XL
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 ///
cc61c64b
XL
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 /// ```
cdc7bbd5
XL
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
c1a9b12d 236 #[stable(feature = "hash_slice", since = "1.3.0")]
b039eaaf 237 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
60c5eb7d
XL
238 where
239 Self: Sized,
b039eaaf 240 {
85aaf69f
SL
241 for piece in data {
242 piece.hash(state);
243 }
244 }
1a4d82fc
JJ
245}
246
416331ca 247// Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
416331ca
XL
248pub(crate) mod macros {
249 /// Derive macro generating an impl of the trait `Hash`.
250 #[rustc_builtin_macro]
416331ca
XL
251 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
252 #[allow_internal_unstable(core_intrinsics)]
60c5eb7d
XL
253 pub macro Hash($item:item) {
254 /* compiler built-in */
255 }
416331ca 256}
416331ca
XL
257#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
258#[doc(inline)]
259pub use macros::Hash;
260
cc61c64b
XL
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///
04454e1e 271/// This trait provides no guarantees about how the various `write_*` methods are
cdc7bbd5
XL
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
04454e1e
FG
274/// equivalent to four calls of [`write_u8`]. Nor can you assume that adjacent
275/// `write` calls are merged, so it's possible, for example, that
276/// ```
277/// # fn foo(hasher: &mut impl std::hash::Hasher) {
278/// hasher.write(&[1, 2]);
279/// hasher.write(&[3, 4, 5, 6]);
280/// # }
281/// ```
282/// and
283/// ```
284/// # fn foo(hasher: &mut impl std::hash::Hasher) {
285/// hasher.write(&[1, 2, 3, 4]);
286/// hasher.write(&[5, 6]);
287/// # }
288/// ```
289/// end up producing different hashes.
290///
291/// Thus to produce the same hash value, [`Hash`] implementations must ensure
292/// for equivalent items that exactly the same sequence of calls is made -- the
293/// same methods with the same parameters in the same order.
cdc7bbd5 294///
cc61c64b
XL
295/// # Examples
296///
297/// ```
298/// use std::collections::hash_map::DefaultHasher;
299/// use std::hash::Hasher;
300///
301/// let mut hasher = DefaultHasher::new();
302///
303/// hasher.write_u32(1989);
304/// hasher.write_u8(11);
305/// hasher.write_u8(9);
306/// hasher.write(b"Huh?");
307///
308/// println!("Hash is {:x}!", hasher.finish());
309/// ```
310///
1b1a35ee
XL
311/// [`finish`]: Hasher::finish
312/// [`write`]: Hasher::write
313/// [`write_u8`]: Hasher::write_u8
cdc7bbd5 314/// [`write_u32`]: Hasher::write_u32
85aaf69f 315#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 316pub trait Hasher {
3b2f2976
XL
317 /// Returns the hash value for the values written so far.
318 ///
319 /// Despite its name, the method does not reset the hasher’s internal
320 /// state. Additional [`write`]s will continue from the current value.
321 /// If you need to start a fresh hash value, you will have to create
322 /// a new hasher.
cc61c64b
XL
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// use std::collections::hash_map::DefaultHasher;
328 /// use std::hash::Hasher;
329 ///
330 /// let mut hasher = DefaultHasher::new();
331 /// hasher.write(b"Cool!");
332 ///
333 /// println!("Hash is {:x}!", hasher.finish());
334 /// ```
3b2f2976 335 ///
1b1a35ee 336 /// [`write`]: Hasher::write
c34b1796 337 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
338 fn finish(&self) -> u64;
339
c30ab7b3 340 /// Writes some data into this `Hasher`.
cc61c64b
XL
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use std::collections::hash_map::DefaultHasher;
346 /// use std::hash::Hasher;
347 ///
348 /// let mut hasher = DefaultHasher::new();
349 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
350 ///
351 /// hasher.write(&data);
352 ///
353 /// println!("Hash is {:x}!", hasher.finish());
354 /// ```
04454e1e
FG
355 ///
356 /// # Note to Implementers
357 ///
358 /// You generally should not do length-prefixing as part of implementing
359 /// this method. It's up to the [`Hash`] implementation to call
360 /// [`Hasher::write_length_prefix`] before sequences that need it.
85aaf69f
SL
361 #[stable(feature = "rust1", since = "1.0.0")]
362 fn write(&mut self, bytes: &[u8]);
363
cc61c64b 364 /// Writes a single `u8` into this hasher.
85aaf69f 365 #[inline]
c1a9b12d 366 #[stable(feature = "hasher_write", since = "1.3.0")]
b039eaaf
SL
367 fn write_u8(&mut self, i: u8) {
368 self.write(&[i])
369 }
c30ab7b3 370 /// Writes a single `u16` into this hasher.
85aaf69f 371 #[inline]
c1a9b12d 372 #[stable(feature = "hasher_write", since = "1.3.0")]
85aaf69f 373 fn write_u16(&mut self, i: u16) {
48663c56 374 self.write(&i.to_ne_bytes())
85aaf69f 375 }
c30ab7b3 376 /// Writes a single `u32` into this hasher.
85aaf69f 377 #[inline]
c1a9b12d 378 #[stable(feature = "hasher_write", since = "1.3.0")]
85aaf69f 379 fn write_u32(&mut self, i: u32) {
48663c56 380 self.write(&i.to_ne_bytes())
85aaf69f 381 }
c30ab7b3 382 /// Writes a single `u64` into this hasher.
85aaf69f 383 #[inline]
c1a9b12d 384 #[stable(feature = "hasher_write", since = "1.3.0")]
85aaf69f 385 fn write_u64(&mut self, i: u64) {
48663c56 386 self.write(&i.to_ne_bytes())
85aaf69f 387 }
32a655c1
SL
388 /// Writes a single `u128` into this hasher.
389 #[inline]
0531ce1d 390 #[stable(feature = "i128", since = "1.26.0")]
32a655c1 391 fn write_u128(&mut self, i: u128) {
48663c56 392 self.write(&i.to_ne_bytes())
32a655c1 393 }
c30ab7b3 394 /// Writes a single `usize` into this hasher.
85aaf69f 395 #[inline]
c1a9b12d 396 #[stable(feature = "hasher_write", since = "1.3.0")]
85aaf69f 397 fn write_usize(&mut self, i: usize) {
48663c56 398 self.write(&i.to_ne_bytes())
85aaf69f
SL
399 }
400
c30ab7b3 401 /// Writes a single `i8` into this hasher.
85aaf69f 402 #[inline]
c1a9b12d 403 #[stable(feature = "hasher_write", since = "1.3.0")]
b039eaaf
SL
404 fn write_i8(&mut self, i: i8) {
405 self.write_u8(i as u8)
406 }
c30ab7b3 407 /// Writes a single `i16` into this hasher.
85aaf69f 408 #[inline]
c1a9b12d 409 #[stable(feature = "hasher_write", since = "1.3.0")]
b039eaaf 410 fn write_i16(&mut self, i: i16) {
f035d41b 411 self.write_u16(i as u16)
b039eaaf 412 }
c30ab7b3 413 /// Writes a single `i32` into this hasher.
85aaf69f 414 #[inline]
c1a9b12d 415 #[stable(feature = "hasher_write", since = "1.3.0")]
b039eaaf 416 fn write_i32(&mut self, i: i32) {
f035d41b 417 self.write_u32(i as u32)
b039eaaf 418 }
c30ab7b3 419 /// Writes a single `i64` into this hasher.
85aaf69f 420 #[inline]
c1a9b12d 421 #[stable(feature = "hasher_write", since = "1.3.0")]
b039eaaf 422 fn write_i64(&mut self, i: i64) {
f035d41b 423 self.write_u64(i as u64)
b039eaaf 424 }
32a655c1
SL
425 /// Writes a single `i128` into this hasher.
426 #[inline]
0531ce1d 427 #[stable(feature = "i128", since = "1.26.0")]
32a655c1 428 fn write_i128(&mut self, i: i128) {
f035d41b 429 self.write_u128(i as u128)
32a655c1 430 }
c30ab7b3 431 /// Writes a single `isize` into this hasher.
85aaf69f 432 #[inline]
c1a9b12d 433 #[stable(feature = "hasher_write", since = "1.3.0")]
b039eaaf 434 fn write_isize(&mut self, i: isize) {
f035d41b 435 self.write_usize(i as usize)
b039eaaf 436 }
04454e1e
FG
437
438 /// Writes a length prefix into this hasher, as part of being prefix-free.
439 ///
440 /// If you're implementing [`Hash`] for a custom collection, call this before
441 /// writing its contents to this `Hasher`. That way
442 /// `(collection![1, 2, 3], collection![4, 5])` and
443 /// `(collection![1, 2], collection![3, 4, 5])` will provide different
444 /// sequences of values to the `Hasher`
445 ///
446 /// The `impl<T> Hash for [T]` includes a call to this method, so if you're
447 /// hashing a slice (or array or vector) via its `Hash::hash` method,
448 /// you should **not** call this yourself.
449 ///
450 /// This method is only for providing domain separation. If you want to
451 /// hash a `usize` that represents part of the *data*, then it's important
452 /// that you pass it to [`Hasher::write_usize`] instead of to this method.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// #![feature(hasher_prefixfree_extras)]
458 /// # // Stubs to make the `impl` below pass the compiler
459 /// # struct MyCollection<T>(Option<T>);
460 /// # impl<T> MyCollection<T> {
461 /// # fn len(&self) -> usize { todo!() }
462 /// # }
463 /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
464 /// # type Item = T;
465 /// # type IntoIter = std::iter::Empty<T>;
466 /// # fn into_iter(self) -> Self::IntoIter { todo!() }
467 /// # }
468 ///
469 /// use std::hash::{Hash, Hasher};
470 /// impl<T: Hash> Hash for MyCollection<T> {
471 /// fn hash<H: Hasher>(&self, state: &mut H) {
472 /// state.write_length_prefix(self.len());
473 /// for elt in self {
474 /// elt.hash(state);
475 /// }
476 /// }
477 /// }
478 /// ```
479 ///
480 /// # Note to Implementers
481 ///
482 /// If you've decided that your `Hasher` is willing to be susceptible to
483 /// Hash-DoS attacks, then you might consider skipping hashing some or all
484 /// of the `len` provided in the name of increased performance.
485 #[inline]
486 #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
487 fn write_length_prefix(&mut self, len: usize) {
488 self.write_usize(len);
489 }
490
491 /// Writes a single `str` into this hasher.
492 ///
493 /// If you're implementing [`Hash`], you generally do not need to call this,
494 /// as the `impl Hash for str` does, so you should prefer that instead.
495 ///
496 /// This includes the domain separator for prefix-freedom, so you should
497 /// **not** call `Self::write_length_prefix` before calling this.
498 ///
499 /// # Note to Implementers
500 ///
501 /// There are at least two reasonable default ways to implement this.
502 /// Which one will be the default is not yet decided, so for now
503 /// you probably want to override it specifically.
504 ///
505 /// ## The general answer
506 ///
507 /// It's always correct to implement this with a length prefix:
508 ///
509 /// ```
510 /// # #![feature(hasher_prefixfree_extras)]
511 /// # struct Foo;
512 /// # impl std::hash::Hasher for Foo {
513 /// # fn finish(&self) -> u64 { unimplemented!() }
514 /// # fn write(&mut self, _bytes: &[u8]) { unimplemented!() }
515 /// fn write_str(&mut self, s: &str) {
516 /// self.write_length_prefix(s.len());
517 /// self.write(s.as_bytes());
518 /// }
519 /// # }
520 /// ```
521 ///
522 /// And, if your `Hasher` works in `usize` chunks, this is likely a very
523 /// efficient way to do it, as anything more complicated may well end up
524 /// slower than just running the round with the length.
525 ///
526 /// ## If your `Hasher` works byte-wise
527 ///
528 /// One nice thing about `str` being UTF-8 is that the `b'\xFF'` byte
529 /// never happens. That means that you can append that to the byte stream
530 /// being hashed and maintain prefix-freedom:
531 ///
532 /// ```
533 /// # #![feature(hasher_prefixfree_extras)]
534 /// # struct Foo;
535 /// # impl std::hash::Hasher for Foo {
536 /// # fn finish(&self) -> u64 { unimplemented!() }
537 /// # fn write(&mut self, _bytes: &[u8]) { unimplemented!() }
538 /// fn write_str(&mut self, s: &str) {
539 /// self.write(s.as_bytes());
540 /// self.write_u8(0xff);
541 /// }
542 /// # }
543 /// ```
544 ///
545 /// This does require that your implementation not add extra padding, and
546 /// thus generally requires that you maintain a buffer, running a round
547 /// only once that buffer is full (or `finish` is called).
548 ///
549 /// That's because if `write` pads data out to a fixed chunk size, it's
550 /// likely that it does it in such a way that `"a"` and `"a\x00"` would
551 /// end up hashing the same sequence of things, introducing conflicts.
552 #[inline]
553 #[unstable(feature = "hasher_prefixfree_extras", issue = "96762")]
554 fn write_str(&mut self, s: &str) {
555 self.write(s.as_bytes());
556 self.write_u8(0xff);
557 }
1a4d82fc
JJ
558}
559
ea8adc8c 560#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
0bf4aa26 561impl<H: Hasher + ?Sized> Hasher for &mut H {
ea8adc8c
XL
562 fn finish(&self) -> u64 {
563 (**self).finish()
564 }
565 fn write(&mut self, bytes: &[u8]) {
566 (**self).write(bytes)
567 }
568 fn write_u8(&mut self, i: u8) {
569 (**self).write_u8(i)
570 }
571 fn write_u16(&mut self, i: u16) {
572 (**self).write_u16(i)
573 }
574 fn write_u32(&mut self, i: u32) {
575 (**self).write_u32(i)
576 }
577 fn write_u64(&mut self, i: u64) {
578 (**self).write_u64(i)
579 }
580 fn write_u128(&mut self, i: u128) {
581 (**self).write_u128(i)
582 }
583 fn write_usize(&mut self, i: usize) {
584 (**self).write_usize(i)
585 }
586 fn write_i8(&mut self, i: i8) {
587 (**self).write_i8(i)
588 }
589 fn write_i16(&mut self, i: i16) {
590 (**self).write_i16(i)
591 }
592 fn write_i32(&mut self, i: i32) {
593 (**self).write_i32(i)
594 }
595 fn write_i64(&mut self, i: i64) {
596 (**self).write_i64(i)
597 }
598 fn write_i128(&mut self, i: i128) {
599 (**self).write_i128(i)
600 }
601 fn write_isize(&mut self, i: isize) {
602 (**self).write_isize(i)
603 }
04454e1e
FG
604 fn write_length_prefix(&mut self, len: usize) {
605 (**self).write_length_prefix(len)
606 }
607 fn write_str(&mut self, s: &str) {
608 (**self).write_str(s)
609 }
ea8adc8c
XL
610}
611
cc61c64b
XL
612/// A trait for creating instances of [`Hasher`].
613///
0731742a 614/// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
cc61c64b
XL
615/// [`Hasher`]s for each key such that they are hashed independently of one
616/// another, since [`Hasher`]s contain state.
617///
618/// For each instance of `BuildHasher`, the [`Hasher`]s created by
619/// [`build_hasher`] should be identical. That is, if the same stream of bytes
620/// is fed into each hasher, the same output will also be generated.
621///
622/// # Examples
623///
624/// ```
625/// use std::collections::hash_map::RandomState;
626/// use std::hash::{BuildHasher, Hasher};
627///
628/// let s = RandomState::new();
629/// let mut hasher_1 = s.build_hasher();
630/// let mut hasher_2 = s.build_hasher();
9cc50fc6 631///
cc61c64b
XL
632/// hasher_1.write_u32(8128);
633/// hasher_2.write_u32(8128);
634///
635/// assert_eq!(hasher_1.finish(), hasher_2.finish());
636/// ```
637///
1b1a35ee 638/// [`build_hasher`]: BuildHasher::build_hasher
cc61c64b 639/// [`HashMap`]: ../../std/collections/struct.HashMap.html
9cc50fc6
SL
640#[stable(since = "1.7.0", feature = "build_hasher")]
641pub trait BuildHasher {
642 /// Type of the hasher that will be created.
643 #[stable(since = "1.7.0", feature = "build_hasher")]
644 type Hasher: Hasher;
645
646 /// Creates a new hasher.
5bcae85e 647 ///
cc61c64b
XL
648 /// Each call to `build_hasher` on the same instance should produce identical
649 /// [`Hasher`]s.
650 ///
5bcae85e
SL
651 /// # Examples
652 ///
653 /// ```
654 /// use std::collections::hash_map::RandomState;
655 /// use std::hash::BuildHasher;
656 ///
657 /// let s = RandomState::new();
658 /// let new_s = s.build_hasher();
659 /// ```
9cc50fc6
SL
660 #[stable(since = "1.7.0", feature = "build_hasher")]
661 fn build_hasher(&self) -> Self::Hasher;
136023e0
XL
662
663 /// Calculates the hash of a single value.
664 ///
665 /// This is intended as a convenience for code which *consumes* hashes, such
666 /// as the implementation of a hash table or in unit tests that check
667 /// whether a custom [`Hash`] implementation behaves as expected.
668 ///
669 /// This must not be used in any code which *creates* hashes, such as in an
670 /// implementation of [`Hash`]. The way to create a combined hash of
671 /// multiple values is to call [`Hash::hash`] multiple times using the same
672 /// [`Hasher`], not to call this method repeatedly and combine the results.
673 ///
674 /// # Example
675 ///
676 /// ```
677 /// #![feature(build_hasher_simple_hash_one)]
678 ///
679 /// use std::cmp::{max, min};
680 /// use std::hash::{BuildHasher, Hash, Hasher};
681 /// struct OrderAmbivalentPair<T: Ord>(T, T);
682 /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
683 /// fn hash<H: Hasher>(&self, hasher: &mut H) {
684 /// min(&self.0, &self.1).hash(hasher);
685 /// max(&self.0, &self.1).hash(hasher);
686 /// }
687 /// }
688 ///
689 /// // Then later, in a `#[test]` for the type...
690 /// let bh = std::collections::hash_map::RandomState::new();
691 /// assert_eq!(
692 /// bh.hash_one(OrderAmbivalentPair(1, 2)),
693 /// bh.hash_one(OrderAmbivalentPair(2, 1))
694 /// );
695 /// assert_eq!(
696 /// bh.hash_one(OrderAmbivalentPair(10, 2)),
697 /// bh.hash_one(&OrderAmbivalentPair(2, 10))
698 /// );
699 /// ```
700 #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
701 fn hash_one<T: Hash>(&self, x: T) -> u64
702 where
703 Self: Sized,
704 {
705 let mut hasher = self.build_hasher();
706 x.hash(&mut hasher);
707 hasher.finish()
708 }
9cc50fc6
SL
709}
710
cc61c64b
XL
711/// Used to create a default [`BuildHasher`] instance for types that implement
712/// [`Hasher`] and [`Default`].
9cc50fc6 713///
cc61c64b
XL
714/// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
715/// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
716/// defined.
717///
718/// Any `BuildHasherDefault` is [zero-sized]. It can be created with
1b1a35ee 719/// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
cc61c64b
XL
720/// [`HashSet`], this doesn't need to be done, since they implement appropriate
721/// [`Default`] instances themselves.
476ff2be
SL
722///
723/// # Examples
724///
725/// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
726/// [`HashMap`]:
727///
728/// ```
729/// use std::collections::HashMap;
730/// use std::hash::{BuildHasherDefault, Hasher};
731///
732/// #[derive(Default)]
733/// struct MyHasher;
734///
735/// impl Hasher for MyHasher {
736/// fn write(&mut self, bytes: &[u8]) {
737/// // Your hashing algorithm goes here!
738/// unimplemented!()
739/// }
740///
741/// fn finish(&self) -> u64 {
742/// // Your hashing algorithm goes here!
743/// unimplemented!()
744/// }
745/// }
746///
747/// type MyBuildHasher = BuildHasherDefault<MyHasher>;
748///
749/// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
750/// ```
751///
1b1a35ee 752/// [method.default]: BuildHasherDefault::default
32a655c1 753/// [`HashMap`]: ../../std/collections/struct.HashMap.html
cc61c64b
XL
754/// [`HashSet`]: ../../std/collections/struct.HashSet.html
755/// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
9cc50fc6 756#[stable(since = "1.7.0", feature = "build_hasher")]
5099ac24 757pub struct BuildHasherDefault<H>(marker::PhantomData<fn() -> H>);
9cc50fc6 758
54a0048b
SL
759#[stable(since = "1.9.0", feature = "core_impl_debug")]
760impl<H> fmt::Debug for BuildHasherDefault<H> {
48663c56 761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
cdc7bbd5 762 f.debug_struct("BuildHasherDefault").finish()
54a0048b
SL
763 }
764}
765
9cc50fc6
SL
766#[stable(since = "1.7.0", feature = "build_hasher")]
767impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
768 type Hasher = H;
769
770 fn build_hasher(&self) -> H {
771 H::default()
772 }
773}
774
775#[stable(since = "1.7.0", feature = "build_hasher")]
776impl<H> Clone for BuildHasherDefault<H> {
777 fn clone(&self) -> BuildHasherDefault<H> {
778 BuildHasherDefault(marker::PhantomData)
779 }
780}
781
782#[stable(since = "1.7.0", feature = "build_hasher")]
94222f64
XL
783#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
784impl<H> const Default for BuildHasherDefault<H> {
9cc50fc6
SL
785 fn default() -> BuildHasherDefault<H> {
786 BuildHasherDefault(marker::PhantomData)
787 }
788}
789
8faf50e0
XL
790#[stable(since = "1.29.0", feature = "build_hasher_eq")]
791impl<H> PartialEq for BuildHasherDefault<H> {
792 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
793 true
794 }
795}
796
797#[stable(since = "1.29.0", feature = "build_hasher_eq")]
798impl<H> Eq for BuildHasherDefault<H> {}
799
1a4d82fc 800mod impls {
48663c56
XL
801 use crate::mem;
802 use crate::slice;
803
85aaf69f 804 use super::*;
1a4d82fc 805
85aaf69f
SL
806 macro_rules! impl_write {
807 ($(($ty:ident, $meth:ident),)*) => {$(
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl Hash for $ty {
6a06907d 810 #[inline]
85aaf69f
SL
811 fn hash<H: Hasher>(&self, state: &mut H) {
812 state.$meth(*self)
813 }
814
6a06907d 815 #[inline]
85aaf69f 816 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
9cc50fc6 817 let newlen = data.len() * mem::size_of::<$ty>();
85aaf69f 818 let ptr = data.as_ptr() as *const u8;
f9f354fc
XL
819 // SAFETY: `ptr` is valid and aligned, as this macro is only used
820 // for numeric primitives which have no padding. The new slice only
821 // spans across `data` and is never mutated, and its total size is the
822 // same as the original `data` so it can't be over `isize::MAX`.
85aaf69f 823 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
1a4d82fc
JJ
824 }
825 }
85aaf69f 826 )*}
1a4d82fc
JJ
827 }
828
85aaf69f
SL
829 impl_write! {
830 (u8, write_u8),
831 (u16, write_u16),
832 (u32, write_u32),
833 (u64, write_u64),
834 (usize, write_usize),
835 (i8, write_i8),
836 (i16, write_i16),
837 (i32, write_i32),
838 (i64, write_i64),
839 (isize, write_isize),
32a655c1
SL
840 (u128, write_u128),
841 (i128, write_i128),
842 }
1a4d82fc 843
85aaf69f
SL
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl Hash for bool {
6a06907d 846 #[inline]
85aaf69f
SL
847 fn hash<H: Hasher>(&self, state: &mut H) {
848 state.write_u8(*self as u8)
1a4d82fc
JJ
849 }
850 }
851
85aaf69f
SL
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl Hash for char {
6a06907d 854 #[inline]
85aaf69f
SL
855 fn hash<H: Hasher>(&self, state: &mut H) {
856 state.write_u32(*self as u32)
1a4d82fc
JJ
857 }
858 }
859
85aaf69f
SL
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl Hash for str {
6a06907d 862 #[inline]
85aaf69f 863 fn hash<H: Hasher>(&self, state: &mut H) {
04454e1e 864 state.write_str(self);
1a4d82fc
JJ
865 }
866 }
867
94b46f34
XL
868 #[stable(feature = "never_hash", since = "1.29.0")]
869 impl Hash for ! {
6a06907d 870 #[inline]
94b46f34
XL
871 fn hash<H: Hasher>(&self, _: &mut H) {
872 *self
873 }
874 }
875
1a4d82fc
JJ
876 macro_rules! impl_hash_tuple {
877 () => (
85aaf69f
SL
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl Hash for () {
6a06907d 880 #[inline]
85aaf69f 881 fn hash<H: Hasher>(&self, _state: &mut H) {}
1a4d82fc
JJ
882 }
883 );
884
885 ( $($name:ident)+) => (
923072b8
FG
886 maybe_tuple_doc! {
887 $($name)+ @
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
890 #[allow(non_snake_case)]
891 #[inline]
892 fn hash<S: Hasher>(&self, state: &mut S) {
893 let ($(ref $name,)+) = *self;
894 $($name.hash(state);)+
895 }
1a4d82fc
JJ
896 }
897 }
898 );
899 }
900
923072b8
FG
901 macro_rules! maybe_tuple_doc {
902 ($a:ident @ #[$meta:meta] $item:item) => {
903 #[cfg_attr(not(bootstrap), doc(tuple_variadic))]
904 #[doc = "This trait is implemented for tuples up to twelve items long."]
905 #[$meta]
906 $item
907 };
908 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
909 #[doc(hidden)]
910 #[$meta]
911 $item
912 };
913 }
914
041b39d2
XL
915 macro_rules! last_type {
916 ($a:ident,) => { $a };
917 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
918 }
919
1a4d82fc 920 impl_hash_tuple! {}
923072b8
FG
921 impl_hash_tuple! { T }
922 impl_hash_tuple! { T B }
923 impl_hash_tuple! { T B C }
924 impl_hash_tuple! { T B C D }
925 impl_hash_tuple! { T B C D E }
926 impl_hash_tuple! { T B C D E F }
927 impl_hash_tuple! { T B C D E F G }
928 impl_hash_tuple! { T B C D E F G H }
929 impl_hash_tuple! { T B C D E F G H I }
930 impl_hash_tuple! { T B C D E F G H I J }
931 impl_hash_tuple! { T B C D E F G H I J K }
932 impl_hash_tuple! { T B C D E F G H I J K L }
1a4d82fc 933
85aaf69f
SL
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<T: Hash> Hash for [T] {
6a06907d 936 #[inline]
85aaf69f 937 fn hash<H: Hasher>(&self, state: &mut H) {
04454e1e 938 state.write_length_prefix(self.len());
85aaf69f 939 Hash::hash_slice(self, state)
1a4d82fc
JJ
940 }
941 }
942
85aaf69f 943 #[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 944 impl<T: ?Sized + Hash> Hash for &T {
6a06907d 945 #[inline]
85aaf69f 946 fn hash<H: Hasher>(&self, state: &mut H) {
1a4d82fc
JJ
947 (**self).hash(state);
948 }
949 }
950
85aaf69f 951 #[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 952 impl<T: ?Sized + Hash> Hash for &mut T {
6a06907d 953 #[inline]
85aaf69f 954 fn hash<H: Hasher>(&self, state: &mut H) {
1a4d82fc
JJ
955 (**self).hash(state);
956 }
957 }
958
85aaf69f 959 #[stable(feature = "rust1", since = "1.0.0")]
abe05a73 960 impl<T: ?Sized> Hash for *const T {
6a06907d 961 #[inline]
85aaf69f 962 fn hash<H: Hasher>(&self, state: &mut H) {
cdc7bbd5 963 let (address, metadata) = self.to_raw_parts();
5e7ed085 964 state.write_usize(address.addr());
cdc7bbd5 965 metadata.hash(state);
1a4d82fc
JJ
966 }
967 }
968
85aaf69f 969 #[stable(feature = "rust1", since = "1.0.0")]
abe05a73 970 impl<T: ?Sized> Hash for *mut T {
6a06907d 971 #[inline]
85aaf69f 972 fn hash<H: Hasher>(&self, state: &mut H) {
cdc7bbd5 973 let (address, metadata) = self.to_raw_parts();
5e7ed085 974 state.write_usize(address.addr());
cdc7bbd5 975 metadata.hash(state);
1a4d82fc
JJ
976 }
977 }
978}