striped-lock 0.1.0

Striped Lock for Rust
Documentation
// Copyright (c) 2024 Mek101
//
// 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 https://mozilla.org/MPL/2.0/.

use std::hash::{BuildHasher, Hash};

pub(crate) const MAX_BATCH_KEYS: usize = 4;

/// A batch of keys.
pub trait KeyBatch<K, H>
where
    H: BuildHasher,
    K: Hash,
{
    /// Transform the batch into an array of hashes.
    fn into_hash_array(self, hasher_builder: &H) -> ([u64; MAX_BATCH_KEYS], usize);
}

impl<K, H> KeyBatch<K, H> for (K,)
where
    H: BuildHasher,
    K: Hash,
{
    fn into_hash_array(self, hasher_builder: &H) -> ([u64; MAX_BATCH_KEYS], usize) {
        let mut buf = [0; MAX_BATCH_KEYS];
        buf[0] = hasher_builder.hash_one(self.0);
        (buf, 1)
    }
}

impl<K, H> KeyBatch<K, H> for (K, K)
where
    H: BuildHasher,
    K: Hash,
{
    fn into_hash_array(self, hasher_builder: &H) -> ([u64; MAX_BATCH_KEYS], usize) {
        let mut buf = [0; MAX_BATCH_KEYS];
        buf[0] = hasher_builder.hash_one(self.0);
        buf[1] = hasher_builder.hash_one(self.1);
        (buf, 2)
    }
}

impl<K, H> KeyBatch<K, H> for (K, K, K)
where
    H: BuildHasher,
    K: Hash,
{
    fn into_hash_array(self, hasher_builder: &H) -> ([u64; MAX_BATCH_KEYS], usize) {
        let mut buf = [0; MAX_BATCH_KEYS];
        buf[0] = hasher_builder.hash_one(self.0);
        buf[1] = hasher_builder.hash_one(self.1);
        buf[2] = hasher_builder.hash_one(self.2);
        (buf, 3)
    }
}

impl<K, H> KeyBatch<K, H> for (K, K, K, K)
where
    H: BuildHasher,
    K: Hash,
{
    fn into_hash_array(self, hasher_builder: &H) -> ([u64; MAX_BATCH_KEYS], usize) {
        let mut buf = [0; MAX_BATCH_KEYS];
        buf[0] = hasher_builder.hash_one(self.0);
        buf[1] = hasher_builder.hash_one(self.1);
        buf[2] = hasher_builder.hash_one(self.2);
        buf[3] = hasher_builder.hash_one(self.3);
        (buf, 4)
    }
}