dyn_hash/lib.rs
1//! [![github]](https://github.com/dtolnay/dyn-hash) [![crates-io]](https://crates.io/crates/dyn-hash) [![docs-rs]](https://docs.rs/dyn-hash)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
9//! This crate provides a [`DynHash`] trait that can be used in trait objects.
10//! Types that implement the standard library's [`std::hash::Hash`] trait are
11//! automatically usable by a `DynHash` trait object.
12//!
13//! # Example
14//!
15//! ```
16//! use dyn_hash::DynHash;
17//!
18//! trait MyTrait: DynHash {
19//! /* ... */
20//! }
21//!
22//! // Implement std::hash::Hash for dyn MyTrait
23//! dyn_hash::hash_trait_object!(MyTrait);
24//!
25//! // Now data structures containing Box<dyn MyTrait> can derive Hash:
26//! #[derive(Hash)]
27//! struct Container {
28//! trait_object: Box<dyn MyTrait>,
29//! }
30//! ```
31//!
32//! Without the dyn-hash crate, a trait `trait MyTrait: std::hash::Hash {...}`
33//! would not be dyn-compatible (`dyn MyTrait`).
34//!
35//! ```text
36//! error[E0038]: the trait `MyTrait` is not dyn compatible
37//! --> src/main.rs:7:12
38//! |
39//! 7 | let _: &dyn MyTrait;
40//! | ^^^^^^^^^^^^ `MyTrait` is not dyn compatible
41//! |
42//! note: for a trait to be dyn compatible it needs to allow building a vtable
43//! for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
44//! --> $SYSROOT/lib/rustlib/src/rust/library/core/src/hash/mod.rs:199:8
45//! |
46//! | fn hash<H: Hasher>(&self, state: &mut H);
47//! | ^^^^ ...because method `hash` has generic type parameters
48//! ```
49
50#![doc(html_root_url = "https://docs.rs/dyn-hash/0.2.2")]
51#![no_std]
52
53#[cfg(doc)]
54extern crate core as std;
55
56mod macros;
57
58use core::hash::{Hash, Hasher};
59
60/// This trait is implemented for any type that implements [`std::hash::Hash`].
61pub trait DynHash: sealed::Sealed {
62 fn dyn_hash(&self, state: &mut dyn Hasher);
63}
64
65impl<T: Hash + ?Sized> DynHash for T {
66 fn dyn_hash(&self, mut state: &mut dyn Hasher) {
67 Hash::hash(self, &mut state);
68 }
69}
70
71hash_trait_object!(DynHash);
72
73// Not public API. Referenced by macro-generated code.
74#[doc(hidden)]
75pub mod __private {
76 pub use core::hash::{Hash, Hasher};
77 pub use core::marker::{Send, Sync};
78}
79
80mod sealed {
81 use core::hash::Hash;
82
83 pub trait Sealed {}
84 impl<T: Hash + ?Sized> Sealed for T {}
85}