lance_core/utils/hash.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4use std::hash::Hasher;
5
6/// A wrapper for `&[u8]` to allow byte slices as hash keys.
7///
8/// ```
9/// use lance_core::utils::hash::U8SliceKey;
10/// use std::collections::HashMap;
11///
12/// let mut map: HashMap<U8SliceKey, i32> = HashMap::new();
13/// map.insert(U8SliceKey(&[1, 2, 3]), 42);
14///
15/// assert_eq!(map.get(&U8SliceKey(&[1, 2, 3])), Some(&42));
16/// assert_eq!(map.get(&U8SliceKey(&[1, 2, 4])), None);
17///
18/// // Equality is based on slice contents
19/// assert_eq!(U8SliceKey(&[1, 2, 3]), U8SliceKey(&[1, 2, 3]));
20/// assert_ne!(U8SliceKey(&[1, 2, 3]), U8SliceKey(&[1, 2, 4]));
21/// ```
22#[derive(Debug, Eq)]
23pub struct U8SliceKey<'a>(pub &'a [u8]);
24
25impl PartialEq for U8SliceKey<'_> {
26 fn eq(&self, other: &Self) -> bool {
27 self.0 == other.0
28 }
29}
30
31impl std::hash::Hash for U8SliceKey<'_> {
32 fn hash<H: Hasher>(&self, state: &mut H) {
33 self.0.hash(state);
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40 use std::collections::HashMap;
41
42 #[test]
43 fn test_u8_slice_key() {
44 // Test cases not in doctest: key not found, inequality
45 let mut map = HashMap::new();
46 map.insert(U8SliceKey(&[1, 2, 3]), 42);
47 assert_eq!(map.get(&U8SliceKey(&[4, 5, 6])), None);
48 assert_ne!(U8SliceKey(&[1]), U8SliceKey(&[2]));
49 }
50}