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