Skip to main content

reifydb_value/util/
hash.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use core::hash::{Hash, Hasher};
5
6use serde::{Deserialize, Serialize};
7use xxhash_rust::xxh3;
8
9#[repr(transparent)]
10#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
11#[serde(transparent)]
12pub struct Hash64(pub u64);
13
14impl From<u64> for Hash64 {
15	fn from(value: u64) -> Self {
16		Hash64(value)
17	}
18}
19
20impl From<Hash64> for u64 {
21	fn from(hash: Hash64) -> Self {
22		hash.0
23	}
24}
25
26impl Hash for Hash64 {
27	fn hash<H: Hasher>(&self, state: &mut H) {
28		state.write_u64(self.0)
29	}
30}
31
32#[repr(transparent)]
33#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
34#[serde(transparent)]
35pub struct Hash128(pub u128);
36
37impl From<u128> for Hash128 {
38	fn from(value: u128) -> Self {
39		Hash128(value)
40	}
41}
42
43impl From<Hash128> for u128 {
44	fn from(hash: Hash128) -> Self {
45		hash.0
46	}
47}
48
49impl Hash for Hash128 {
50	fn hash<H: Hasher>(&self, state: &mut H) {
51		state.write_u128(self.0)
52	}
53}
54
55impl Hash128 {
56	#[inline]
57	pub fn to_hex_string_prefixed(self) -> String {
58		const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
59		let mut buf = String::with_capacity(34);
60		buf.push_str("0x");
61		let val = self.0;
62		for i in (0..32).rev() {
63			let nibble = ((val >> (i * 4)) & 0xf) as usize;
64			buf.push(HEX_DIGITS[nibble] as char);
65		}
66		buf
67	}
68}
69
70#[inline]
71pub fn xxh3_64(data: &[u8]) -> Hash64 {
72	Hash64(xxh3::xxh3_64(data))
73}
74
75#[inline]
76pub fn xxh3_128(data: &[u8]) -> Hash128 {
77	Hash128(xxh3::xxh3_128(data))
78}
79
80#[cfg(test)]
81mod tests {
82	use super::*;
83
84	#[test]
85	fn test_xxh3_64() {
86		let data = b"hello world";
87		// Seedless and unsalted, so the digest is stable across processes and cluster nodes.
88		let hash = xxh3_64(data);
89		assert_eq!(hash, xxh3_64(data));
90		assert_ne!(hash, xxh3_64(b"different data"));
91	}
92
93	#[test]
94	fn test_xxh3_128() {
95		let data = b"hello world";
96		let hash = xxh3_128(data);
97		assert_eq!(hash, xxh3_128(data));
98		assert_ne!(hash, xxh3_128(b"different data"));
99	}
100
101	#[test]
102	fn test_hash64_conversions() {
103		let value: u64 = 12345;
104		let hash = Hash64::from(value);
105		assert_eq!(u64::from(hash), value);
106	}
107
108	#[test]
109	fn test_hash128_conversions() {
110		let value: u128 = 123456789;
111		let hash = Hash128::from(value);
112		assert_eq!(u128::from(hash), value);
113	}
114}