Skip to main content

rustolio_db/
key.rs

1//
2// SPDX-License-Identifier: MPL-2.0
3//
4// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9//
10
11use std::hash::{DefaultHasher, Hash, Hasher};
12
13use rustolio_utils::prelude::*;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Decode, Encode)]
16pub struct Key {
17    hash: u64,
18    ty: KeyType,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Decode, Encode)]
22pub enum KeyType {
23    ReadWrite,
24    ReadSecureWrite,
25    SecureReadWrite,
26}
27
28impl Key {
29    pub fn from_value(value: &impl std::hash::Hash, ty: KeyType) -> Self {
30        // Use the same hasher across all peers -> `DefaultHasher::new()` returns `SipHasher13::new_with_keys(0, 0)`
31        let mut hasher = DefaultHasher::new();
32        value.hash(&mut hasher);
33        ty.hash(&mut hasher);
34        let hash = hasher.finish();
35        Self { hash, ty }
36    }
37
38    pub fn hash(&self) -> u64 {
39        self.hash
40    }
41
42    pub fn ty(&self) -> KeyType {
43        self.ty
44    }
45}
46
47// ---- Hash impl
48// This does not actually hash the key as it is already hashed on creation (see `Key::from_value(..)`)
49// Instead the `KeyHasher` just returns the hash contained in the key. The `KeyState` is used in the `crate::store`s HashMap
50
51impl std::hash::Hash for Key {
52    fn hash<H: Hasher>(&self, state: &mut H) {
53        state.write_u64(self.hash);
54    }
55}
56
57pub type KeyState = std::hash::BuildHasherDefault<KeyHasher>;
58
59#[derive(Debug, Default)]
60pub struct KeyHasher {
61    state: u64,
62}
63
64impl Hasher for KeyHasher {
65    fn finish(&self) -> u64 {
66        self.state
67    }
68
69    fn write(&mut self, _: &[u8]) {
70        unreachable!("write_u64 should always be used");
71    }
72
73    fn write_u64(&mut self, i: u64) {
74        self.state = i;
75    }
76}