toad_hash/lib.rs
1//! # toad-hash
2//!
3//! This microcrate contains a no_std and no-alloc `Hasher` implementation
4//! using the Blake2 hash algorithm
5
6// docs
7#![doc(html_root_url = "https://docs.rs/toad-hash/0.1.0")]
8#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
9// -
10// style
11#![allow(clippy::unused_unit)]
12// -
13// deny
14#![deny(missing_docs)]
15#![deny(missing_debug_implementations)]
16#![deny(missing_copy_implementations)]
17#![cfg_attr(not(test), deny(unsafe_code))]
18// -
19// warnings
20#![cfg_attr(not(test), warn(unreachable_pub))]
21// -
22// features
23#![cfg_attr(not(feature = "std"), no_std)]
24
25#[cfg(feature = "alloc")]
26extern crate alloc as std_alloc;
27
28use core::fmt::Debug;
29use core::hash::Hasher;
30
31use blake2::digest::typenum::U8;
32use blake2::{Blake2b, Digest};
33
34/// Heap-allocless [`Hasher`] implementation that uses
35/// the [`blake2`] algo to generate a 64 bit hash.
36///
37/// ```
38/// use core::hash::{Hash, Hasher};
39///
40/// use toad_hash::Blake2Hasher;
41///
42/// let mut hasher_a = Blake2Hasher::new();
43/// let mut hasher_b = Blake2Hasher::new();
44///
45/// let bytes = core::iter::repeat(0u8..255).take(512)
46/// .flatten()
47/// .collect::<Vec<u8>>();
48///
49/// bytes.hash(&mut hasher_a);
50/// bytes.hash(&mut hasher_b);
51/// assert_eq!(hasher_a.finish(), hasher_b.finish());
52///
53/// "hello".hash(&mut hasher_a);
54/// "hello".hash(&mut hasher_b);
55/// assert_eq!(hasher_a.finish(), hasher_b.finish());
56///
57/// 123_u16.hash(&mut hasher_a);
58/// "not 123!".hash(&mut hasher_b);
59/// assert_ne!(hasher_a.finish(), hasher_b.finish());
60/// ```
61#[derive(Default, Clone)]
62pub struct Blake2Hasher(Blake2b<U8>);
63
64impl Blake2Hasher {
65 /// Create a new `Blake2Hasher`
66 pub fn new() -> Self {
67 Self::default()
68 }
69}
70
71impl Debug for Blake2Hasher {
72 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
73 f.debug_tuple("Blake2Hasher")
74 .field(&"<Blake2bCore<U8>>")
75 .finish()
76 }
77}
78
79impl Hasher for Blake2Hasher {
80 fn finish(&self) -> u64 {
81 u64::from_be_bytes(self.0.clone().finalize().into())
82 }
83
84 fn write(&mut self, bytes: &[u8]) {
85 self.0.update(bytes);
86 }
87}