Skip to main content

try_traits/
hash.rs

1//! Try traits for [`core::hash`].
2//!
3//! Note that [`BuildHasher`](core::hash::BuildHasher) isn't implemented because each call to
4//! `build_hasher` should return identical values.
5//!
6//! [`Hasher`] also was not given a `Try` variant as I can see no real use for it (and as it
7//! complicates automatic implementations), , but if there's good reason for one it'll be added.
8use core::hash::{Hash, Hasher};
9
10/// The try trait for [`Hash`].
11pub trait TryHash {
12	/// The type returned in the event of an error.
13	type Error;
14
15	/// The fallible equivalent of [`Hash::hash`].
16	fn try_hash<H: Hasher>(&self, state: &mut H) -> Result<(), Self::Error>;
17
18	/// The fallible equivalent of [`Hash::hash_slice`].
19	fn try_hash_slice<H: Hasher>(data: &[Self], state: &mut H) -> Result<(), Self::Error>
20	where
21		Self: Sized
22	{
23		for piece in data {
24			piece.try_hash(state)?;
25		}
26
27		Ok(())
28	}
29}
30
31impl<T: Hash> TryHash for T {
32	type Error = crate::Infallible;
33
34	#[inline]
35	fn try_hash<H: Hasher>(&self, state: &mut H) -> Result<(), Self::Error> {
36		Ok(self.hash(state))
37	}
38
39	#[inline]
40	fn try_hash_slice<H: Hasher>(data: &[Self], state: &mut H) -> Result<(), Self::Error> {
41		Ok(Self::hash_slice(data, state))
42	}
43}