// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
//! An implementation of SipHash with a 128-bit output.
use core::cmp; use core::hash; use core::marker::PhantomData; use core::mem; use core::ptr; use core::u64;
/// An implementation of SipHash128 2-4. /// /// SipHash is a general-purpose hashing function: it runs at a good /// speed (competitive with Spooky and City) and permits strong _keyed_ /// hashing. This lets you key your hashtables from a strong RNG, such as /// [`rand::os::OsRng`](https://doc.rust-lang.org/rand/rand/os/struct.OsRng.html). /// /// Although the SipHash algorithm is considered to be generally strong, /// it is not intended for cryptographic purposes. As such, all /// cryptographic uses of this implementation are _strongly discouraged_. #[derive(Debug, Clone, Copy, Default)] pubstruct SipHasher(SipHasher24);
#[derive(Debug, Copy)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] struct Hasher<S: Sip> {
k0: u64,
k1: u64,
length: usize, // how many bytes we've processed
state: State, // hash State
tail: u64, // unprocessed bytes le
ntail: usize, // how many bytes in tail are valid
_marker: PhantomData<S>,
}
#[derive(Debug, Clone, Copy)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] struct State { // v0, v2 and v1, v3 show up in pairs in the algorithm, // and simd implementations of SipHash will use vectors // of v02 and v13. By placing them in this order in the struct, // the compiler can pick up on just a few simd optimizations by itself.
v0: u64,
v2: u64,
v1: u64,
v3: u64,
}
/// Loads an integer of the desired type from a byte stream, in LE order. Uses /// `copy_nonoverlapping` to let the compiler generate the most efficient way /// to load it from a possibly unaligned address. /// /// Unsafe because: unchecked indexing at `i..i+size_of(int_ty)`
macro_rules! load_int_le {
($buf:expr, $i:expr, $int_ty:ident) => {{
debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len()); letmut data = 0as $int_ty;
ptr::copy_nonoverlapping(
$buf.as_ptr().add($i),
&mut data as *mut _ as *mut u8,
mem::size_of::<$int_ty>(),
);
data.to_le()
}};
}
/// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the /// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed /// sizes and avoid calling `memcpy`, which is good for speed. /// /// Unsafe because: unchecked indexing at start..start+len #[inline] unsafefn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
debug_assert!(len < 8); letmut i = 0; // current byte index (from LSB) in the output u64 letmut out = 0; if i + 3 < len {
out = load_int_le!(buf, start + i, u32) as u64;
i += 4;
} if i + 1 < len {
out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8);
i += 2
} if i < len {
out |= (*buf.get_unchecked(start + i) as u64) << (i * 8);
i += 1;
}
debug_assert_eq!(i, len);
out
}
impl SipHasher { /// Creates a new `SipHasher` with the two initial keys set to 0. #[inline] pubfn new() -> SipHasher {
SipHasher::new_with_keys(0, 0)
}
/// Creates a `SipHasher` that is keyed off the provided keys. #[inline] pubfn new_with_keys(key0: u64, key1: u64) -> SipHasher {
SipHasher(SipHasher24::new_with_keys(key0, key1))
}
/// Creates a `SipHasher` from a 16 byte key. pubfn new_with_key(key: &[u8; 16]) -> SipHasher { letmut b0 = [0u8; 8]; letmut b1 = [0u8; 8];
b0.copy_from_slice(&key[0..8]);
b1.copy_from_slice(&key[8..16]); let key0 = u64::from_le_bytes(b0); let key1 = u64::from_le_bytes(b1); Self::new_with_keys(key0, key1)
}
/// Get the keys used by this hasher pubfn keys(&self) -> (u64, u64) {
(self.0.hasher.k0, self.0.hasher.k1)
}
/// Get the key used by this hasher as a 16 byte vector pubfn key(&self) -> [u8; 16] { letmut bytes = [0u8; 16];
bytes[0..8].copy_from_slice(&self.0.hasher.k0.to_le_bytes());
bytes[8..16].copy_from_slice(&self.0.hasher.k1.to_le_bytes());
bytes
}
}
impl Hasher128 for SipHasher { /// Return a 128-bit hash #[inline] fn finish128(&self) -> Hash128 { self.0.finish128()
}
}
impl SipHasher13 { /// Creates a new `SipHasher13` with the two initial keys set to 0. #[inline] pubfn new() -> SipHasher13 {
SipHasher13::new_with_keys(0, 0)
}
/// Creates a `SipHasher13` that is keyed off the provided keys. #[inline] pubfn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
SipHasher13 {
hasher: Hasher::new_with_keys(key0, key1),
}
}
/// Creates a `SipHasher13` from a 16 byte key. pubfn new_with_key(key: &[u8; 16]) -> SipHasher13 { letmut b0 = [0u8; 8]; letmut b1 = [0u8; 8];
b0.copy_from_slice(&key[0..8]);
b1.copy_from_slice(&key[8..16]); let key0 = u64::from_le_bytes(b0); let key1 = u64::from_le_bytes(b1); Self::new_with_keys(key0, key1)
}
/// Get the keys used by this hasher pubfn keys(&self) -> (u64, u64) {
(self.hasher.k0, self.hasher.k1)
}
/// Get the key used by this hasher as a 16 byte vector pubfn key(&self) -> [u8; 16] { letmut bytes = [0u8; 16];
bytes[0..8].copy_from_slice(&self.hasher.k0.to_le_bytes());
bytes[8..16].copy_from_slice(&self.hasher.k1.to_le_bytes());
bytes
}
}
impl Hasher128 for SipHasher13 { /// Return a 128-bit hash #[inline] fn finish128(&self) -> Hash128 { self.hasher.finish128()
}
}
impl SipHasher24 { /// Creates a new `SipHasher24` with the two initial keys set to 0. #[inline] pubfn new() -> SipHasher24 {
SipHasher24::new_with_keys(0, 0)
}
/// Creates a `SipHasher24` that is keyed off the provided keys. #[inline] pubfn new_with_keys(key0: u64, key1: u64) -> SipHasher24 {
SipHasher24 {
hasher: Hasher::new_with_keys(key0, key1),
}
}
/// Creates a `SipHasher24` from a 16 byte key. pubfn new_with_key(key: &[u8; 16]) -> SipHasher24 { letmut b0 = [0u8; 8]; letmut b1 = [0u8; 8];
b0.copy_from_slice(&key[0..8]);
b1.copy_from_slice(&key[8..16]); let key0 = u64::from_le_bytes(b0); let key1 = u64::from_le_bytes(b1); Self::new_with_keys(key0, key1)
}
/// Get the keys used by this hasher pubfn keys(&self) -> (u64, u64) {
(self.hasher.k0, self.hasher.k1)
}
/// Get the key used by this hasher as a 16 byte vector pubfn key(&self) -> [u8; 16] { letmut bytes = [0u8; 16];
bytes[0..8].copy_from_slice(&self.hasher.k0.to_le_bytes());
bytes[8..16].copy_from_slice(&self.hasher.k1.to_le_bytes());
bytes
}
}
impl Hasher128 for SipHasher24 { /// Return a 128-bit hash #[inline] fn finish128(&self) -> Hash128 { self.hasher.finish128()
}
}
// A specialized write function for values with size <= 8. // // The hashing of multi-byte integers depends on endianness. E.g.: // - little-endian: `write_u32(0xDDCCBBAA)` == `write([0xAA, 0xBB, 0xCC, 0xDD])` // - big-endian: `write_u32(0xDDCCBBAA)` == `write([0xDD, 0xCC, 0xBB, 0xAA])` // // This function does the right thing for little-endian hardware. On // big-endian hardware `x` must be byte-swapped first to give the right // behaviour. After any byte-swapping, the input must be zero-extended to // 64-bits. The caller is responsible for the byte-swapping and // zero-extension. #[inline] fn short_write<T>(&mutself, _x: T, x: u64) { let size = mem::size_of::<T>(); self.length += size;
// The original number must be zero-extended, not sign-extended.
debug_assert!(if size < 8 { x >> (8 * size) == 0 } else { true });
// The number of bytes needed to fill `self.tail`. let needed = 8 - self.ntail;
self.tail |= x << (8 * self.ntail); if size < needed { self.ntail += size; return;
}
// `self.tail` is full, process it. self.state.v3 ^= self.tail;
S::c_rounds(&mutself.state); self.state.v0 ^= self.tail;
impl<S: Sip> Default for Hasher<S> { /// Creates a `Hasher<S>` with the two initial keys set to 0. #[inline] fn default() -> Hasher<S> {
Hasher::new_with_keys(0, 0)
}
}
impl Hash128 { /// Convert into a 16-bytes vector pubfn as_bytes(&self) -> [u8; 16] { letmut bytes = [0u8; 16]; let h1 = self.h1.to_le(); let h2 = self.h2.to_le(); unsafe {
ptr::copy_nonoverlapping(&h1 as *const _ as *const u8, bytes.as_mut_ptr(), 8);
ptr::copy_nonoverlapping(&h2 as *const _ as *const u8, bytes.as_mut_ptr().add(8), 8);
}
bytes
}
/// Convert into a `u128` #[inline] pubfn as_u128(&self) -> u128 { let h1 = self.h1.to_le(); let h2 = self.h2.to_le();
h1 as u128 | ((h2 as u128) << 64)
}
/// Convert into `(u64, u64)` #[inline] pubfn as_u64(&self) -> (u64, u64) { let h1 = self.h1.to_le(); let h2 = self.h2.to_le();
(h1, h2)
}
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.13 Sekunden
(vorverarbeitet am 2026-07-02)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.