Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce multi hasher support #8

Merged
merged 5 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Unreleased

- Rename `StableHasherResult` to `FromStableHash` (#8)
- Use new-type for returned-hash of `SipHasher128`(`Hash`) (#8)
- Introduce multi hasher support (#8)
- `StableHasher::finish` now returns a small hash instead of being fatal (#6)
- Remove `StableHasher::finalize` (#4)
- Import stable hasher implementation from rustc ([db8aca48129](https://github.com/rust-lang/rust/blob/db8aca48129d86b2623e3ac8cbcf2902d4d313ad/compiler/rustc_data_structures/src/))
21 changes: 20 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,27 @@ mod int_overflow;
mod sip128;
mod stable_hasher;

/// Hashers collection
pub mod hashers {
#[doc(inline)]
pub use super::sip128::{SipHasher128, SipHasher128Hash};

/// Stable 128-bits Sip Hasher
///
/// [`StableHasher`] version of [`SipHasher128`].
///
/// [`StableHasher`]: super::StableHasher
pub type StableSipHasher128 = super::StableHasher<SipHasher128>;
}

#[doc(inline)]
pub use stable_hasher::StableHasher;

#[doc(inline)]
pub use stable_hasher::StableHasherResult;
pub use stable_hasher::FromStableHash;

#[doc(inline)]
pub use stable_hasher::ExtendedHasher;

#[doc(inline)]
pub use hashers::{SipHasher128Hash, StableSipHasher128};
80 changes: 51 additions & 29 deletions src/sip128.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// This code is very hot and uses lots of arithmetic, avoid overflow checks for performance.
// See https://github.com/rust-lang/rust/pull/119440#issuecomment-1874255727
use crate::int_overflow::{DebugStrictAdd, DebugStrictSub};
use crate::ExtendedHasher;

use std::hash::Hasher;
use std::mem::{self, MaybeUninit};
Expand Down Expand Up @@ -40,6 +41,10 @@ const BUFFER_WITH_SPILL_SIZE: usize = BUFFER_WITH_SPILL_CAPACITY * ELEM_SIZE;
// Index of the spill element in the buffer.
const BUFFER_SPILL_INDEX: usize = BUFFER_WITH_SPILL_CAPACITY - 1;

/// Hashing result of [`SipHasher128`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SipHasher128Hash(pub [u64; 2]);

#[derive(Debug, Clone)]
#[repr(C)]
pub struct SipHasher128 {
Expand Down Expand Up @@ -214,28 +219,6 @@ impl SipHasher128 {
hasher
}

#[inline]
pub fn short_write<const LEN: usize>(&mut self, bytes: [u8; LEN]) {
let nbuf = self.nbuf;
debug_assert!(LEN <= 8);
debug_assert!(nbuf < BUFFER_SIZE);
debug_assert!(nbuf + LEN < BUFFER_WITH_SPILL_SIZE);

if nbuf.debug_strict_add(LEN) < BUFFER_SIZE {
unsafe {
// The memcpy call is optimized away because the size is known.
let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf);
ptr::copy_nonoverlapping(bytes.as_ptr(), dst, LEN);
}

self.nbuf = nbuf.debug_strict_add(LEN);

return;
}

unsafe { self.short_write_process_buffer(bytes) }
}

// A specialized write function for values with size <= 8 that should only
// be called when the write would cause the buffer to fill.
//
Expand Down Expand Up @@ -378,13 +361,11 @@ impl SipHasher128 {
}
}

#[inline(always)]
pub fn finish128(mut self) -> [u64; 2] {
SipHasher128::finish128_inner(self.nbuf, &mut self.buf, self.state, self.processed)
}

// A function for finishing the hashing.
//
// SAFETY: `buf` must be initialized up to the byte offset `nbuf`.
#[inline]
fn finish128_inner(
unsafe fn finish128_inner(
Urgau marked this conversation as resolved.
Show resolved Hide resolved
nbuf: usize,
buf: &mut [MaybeUninit<u64>; BUFFER_WITH_SPILL_CAPACITY],
mut state: State,
Expand Down Expand Up @@ -437,6 +418,45 @@ impl SipHasher128 {
}
}

impl Default for SipHasher128 {
fn default() -> SipHasher128 {
SipHasher128::new_with_keys(0, 0)
}
}

impl ExtendedHasher for SipHasher128 {
type Hash = SipHasher128Hash;

#[inline]
fn short_write<const LEN: usize>(&mut self, bytes: [u8; LEN]) {
let nbuf = self.nbuf;
debug_assert!(LEN <= 8);
debug_assert!(nbuf < BUFFER_SIZE);
debug_assert!(nbuf + LEN < BUFFER_WITH_SPILL_SIZE);

if nbuf.debug_strict_add(LEN) < BUFFER_SIZE {
unsafe {
// The memcpy call is optimized away because the size is known.
let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf);
ptr::copy_nonoverlapping(bytes.as_ptr(), dst, LEN);
}

self.nbuf = nbuf.debug_strict_add(LEN);

return;
}

unsafe { self.short_write_process_buffer(bytes) }
}

#[inline(always)]
fn finish(mut self) -> SipHasher128Hash {
SipHasher128Hash(unsafe {
SipHasher128::finish128_inner(self.nbuf, &mut self.buf, self.state, self.processed)
})
}
}

impl Hasher for SipHasher128 {
#[inline]
fn write_u8(&mut self, i: u8) {
Expand Down Expand Up @@ -504,7 +524,9 @@ impl Hasher for SipHasher128 {

fn finish(&self) -> u64 {
let mut buf = self.buf.clone();
let [a, b] = SipHasher128::finish128_inner(self.nbuf, &mut buf, self.state, self.processed);
let [a, b] = unsafe {
SipHasher128::finish128_inner(self.nbuf, &mut buf, self.state, self.processed)
};

// Combining the two halves makes sure we get a good quality hash.
a.wrapping_mul(3).wrapping_add(b).to_le()
Expand Down
22 changes: 13 additions & 9 deletions src/sip128/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ impl<'a> Hash for Bytes<'a> {
}
}

fn hash_with<T: Hash>(mut st: SipHasher128, x: &T) -> [u64; 2] {
fn hash_with<T: Hash>(mut st: SipHasher128, x: &T) -> SipHasher128Hash {
x.hash(&mut st);
st.finish128()
st.finish()
}

fn hash<T: Hash>(x: &T) -> [u64; 2] {
fn hash<T: Hash>(x: &T) -> SipHasher128Hash {
hash_with(SipHasher128::new_with_keys(0, 0), x)
}

Expand Down Expand Up @@ -119,7 +119,7 @@ fn test_siphash_1_3_test_vector() {
| ((TEST_VECTOR[i][15] as u64) << 56),
];

assert_eq!(out, expected);
assert_eq!(out.0, expected);
input.push(i as u8);
}
}
Expand Down Expand Up @@ -253,8 +253,8 @@ fn test_short_write_works() {
h2.write(&test_i128.to_ne_bytes());
h2.write(&test_isize.to_ne_bytes());

let h1_hash = h1.finish128();
let h2_hash = h2.finish128();
let h1_hash = h1.finish();
let h2_hash = h2.finish();

assert_eq!(h1_hash, h2_hash);
}
Expand All @@ -279,8 +279,8 @@ macro_rules! test_fill_buffer {
h2.write(s);
h2.write(x_bytes);

let h1_hash = h1.finish128();
let h2_hash = h2.finish128();
let h1_hash = h1.finish();
let h2_hash = h2.finish();

assert_eq!(h1_hash, h2_hash);
}
Expand All @@ -306,10 +306,14 @@ fn test_fill_buffer() {

#[test]
fn test_finish() {
fn hash<H: Hasher>(h: &H) -> u64 {
h.finish()
}

let mut hasher = SipHasher128::new_with_keys(0, 0);

hasher.write_isize(0xF0);
hasher.write_isize(0xF0010);

assert_eq!(hasher.finish(), hasher.finish());
assert_eq!(hash(&hasher), hash(&hasher));
}
Loading