Skip to main content

reifydb_runtime/
hash.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4//! Hash types and functions for ReifyDB.
5//!
6//! Provides xxHash3 hashing using pure Rust implementation that works
7//! on both native and WASM targets.
8
9use core::hash::{Hash, Hasher};
10
11use serde::{Deserialize, Serialize};
12
13#[repr(transparent)]
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct Hash64(pub u64);
17
18impl From<u64> for Hash64 {
19	fn from(value: u64) -> Self {
20		Hash64(value)
21	}
22}
23
24impl From<Hash64> for u64 {
25	fn from(hash: Hash64) -> Self {
26		hash.0
27	}
28}
29
30impl Hash for Hash64 {
31	fn hash<H: Hasher>(&self, state: &mut H) {
32		state.write_u64(self.0)
33	}
34}
35
36#[repr(transparent)]
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
38#[serde(transparent)]
39pub struct Hash128(pub u128);
40
41impl From<u128> for Hash128 {
42	fn from(value: u128) -> Self {
43		Hash128(value)
44	}
45}
46
47impl From<Hash128> for u128 {
48	fn from(hash: Hash128) -> Self {
49		hash.0
50	}
51}
52
53impl Hash for Hash128 {
54	fn hash<H: Hasher>(&self, state: &mut H) {
55		state.write_u128(self.0)
56	}
57}
58
59/// Compute xxHash3 64-bit hash of data.
60#[inline]
61pub fn xxh3_64(data: &[u8]) -> Hash64 {
62	Hash64(xxhash_rust::xxh3::xxh3_64(data))
63}
64
65/// Compute xxHash3 128-bit hash of data.
66#[inline]
67pub fn xxh3_128(data: &[u8]) -> Hash128 {
68	Hash128(xxhash_rust::xxh3::xxh3_128(data))
69}
70
71#[cfg(test)]
72mod tests {
73	use super::*;
74
75	#[test]
76	fn test_xxh3_64() {
77		let data = b"hello world";
78		let hash = xxh3_64(data);
79		// xxh3_64 should be deterministic
80		assert_eq!(hash, xxh3_64(data));
81		assert_ne!(hash, xxh3_64(b"different data"));
82	}
83
84	#[test]
85	fn test_xxh3_128() {
86		let data = b"hello world";
87		let hash = xxh3_128(data);
88		// xxh3_128 should be deterministic
89		assert_eq!(hash, xxh3_128(data));
90		assert_ne!(hash, xxh3_128(b"different data"));
91	}
92
93	#[test]
94	fn test_hash64_conversions() {
95		let value: u64 = 12345;
96		let hash = Hash64::from(value);
97		assert_eq!(u64::from(hash), value);
98	}
99
100	#[test]
101	fn test_hash128_conversions() {
102		let value: u128 = 123456789;
103		let hash = Hash128::from(value);
104		assert_eq!(u128::from(hash), value);
105	}
106}