rustolio-db 0.1.0

An DB extention for the rustolio HTTP-Server
Documentation
//
// SPDX-License-Identifier: MPL-2.0
//
// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

use std::hash::{DefaultHasher, Hash, Hasher};

use rustolio_utils::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Decode, Encode)]
pub struct Key {
    hash: u64,
    ty: KeyType,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Decode, Encode)]
pub enum KeyType {
    ReadWrite,
    ReadSecureWrite,
    SecureReadWrite,
}

impl Key {
    pub fn from_value(value: &impl std::hash::Hash, ty: KeyType) -> Self {
        // Use the same hasher across all peers -> `DefaultHasher::new()` returns `SipHasher13::new_with_keys(0, 0)`
        let mut hasher = DefaultHasher::new();
        value.hash(&mut hasher);
        ty.hash(&mut hasher);
        let hash = hasher.finish();
        Self { hash, ty }
    }

    pub fn hash(&self) -> u64 {
        self.hash
    }

    pub fn ty(&self) -> KeyType {
        self.ty
    }
}

// ---- Hash impl
// This does not actually hash the key as it is already hashed on creation (see `Key::from_value(..)`)
// Instead the `KeyHasher` just returns the hash contained in the key. The `KeyState` is used in the `crate::store`s HashMap

impl std::hash::Hash for Key {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(self.hash);
    }
}

pub type KeyState = std::hash::BuildHasherDefault<KeyHasher>;

#[derive(Debug, Default)]
pub struct KeyHasher {
    state: u64,
}

impl Hasher for KeyHasher {
    fn finish(&self) -> u64 {
        self.state
    }

    fn write(&mut self, _: &[u8]) {
        unreachable!("write_u64 should always be used");
    }

    fn write_u64(&mut self, i: u64) {
        self.state = i;
    }
}