use std::sync::OnceLock;
use sha2::{Digest, Sha256};
use crate::keytag::redis_slot;
pub const SLOT_COUNT: usize = 16_384;
pub const FAMILY_STRING: u8 = 1;
pub const FAMILY_HASH: u8 = 2;
pub const FAMILY_ZSET: u8 = 3;
pub fn framed_digest(parts: &[&[u8]]) -> [u8; 32] {
let mut hasher = Sha256::new();
for part in parts {
let len = part.len() as u32;
hasher.update(len.to_be_bytes());
hasher.update(part);
}
hasher.finalize().into()
}
pub fn raw_digest(target_key: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(target_key);
hasher.finalize().into()
}
pub fn target_digest_hex(target_key: &[u8]) -> String {
hex::encode(raw_digest(target_key))
}
pub fn ledger_shard(family: &[u8], member: &[u8], shards: u32) -> Option<u32> {
if shards == 0 || !shards.is_power_of_two() {
return None;
}
let value = framed_digest(&[family, member]);
let hash = (u32::from(value[0]) << 24)
| (u32::from(value[1]) << 16)
| (u32::from(value[2]) << 8)
| u32::from(value[3]);
Some(hash & (shards - 1))
}
pub fn record_field(family: &[u8], member: &[u8], nonce: &[u8]) -> [u8; 32] {
framed_digest(&[family, member, nonce])
}
pub fn slot_tokens() -> &'static [String; SLOT_COUNT] {
static TOKENS: OnceLock<Box<[String; SLOT_COUNT]>> = OnceLock::new();
TOKENS
.get_or_init(|| {
let mut tokens: Vec<String> = vec![String::new(); SLOT_COUNT];
let mut assigned = vec![false; SLOT_COUNT];
let mut remaining = SLOT_COUNT;
let mut candidate: u64 = 0;
while remaining > 0 {
let token = format!("s{}", base36(candidate));
candidate += 1;
let slot = redis_slot(token.as_bytes()) as usize;
if !assigned[slot] {
assigned[slot] = true;
tokens[slot] = token;
remaining -= 1;
}
}
let array: Box<[String; SLOT_COUNT]> = tokens
.into_boxed_slice()
.try_into()
.expect("slot token 表长度恒为 SLOT_COUNT");
array
})
.as_ref()
}
fn base36(value: u64) -> String {
const DIGITS: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";
if value == 0 {
return "0".to_owned();
}
let mut n = value;
let mut buf = Vec::new();
while n > 0 {
buf.push(DIGITS[(n % 36) as usize]);
n /= 36;
}
buf.reverse();
String::from_utf8(buf).expect("base36 字符集恒为 ASCII")
}
pub fn ledger_base(
prefix: &str,
target_key: &[u8],
family: &[u8],
member: &[u8],
shards: u32,
) -> Option<String> {
let slot = redis_slot(target_key) as usize;
let token = &slot_tokens()[slot];
let target_hex = target_digest_hex(target_key);
let shard = ledger_shard(family, member, shards)?;
Some(format!("{prefix}:{{{token}}}:{target_hex}:{shard}"))
}
pub fn ledger_slot_matches(ledger_key: &[u8], expected_slot: u16) -> bool {
redis_slot(ledger_key) == expected_slot
}