const BASE32_LOWER: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
fn base32(bytes: &[u8], alphabet: &[u8; 32]) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
let mut acc: u32 = 0;
let mut bits = 0;
for &b in bytes {
acc = (acc << 8) | u32::from(b);
bits += 8;
while bits >= 5 {
bits -= 5;
out.push(alphabet[((acc >> bits) & 31) as usize] as char);
}
}
if bits > 0 {
out.push(alphabet[((acc << (5 - bits)) & 31) as usize] as char);
}
out
}
pub fn base32_lower(bytes: &[u8]) -> String {
base32(bytes, BASE32_LOWER)
}
pub fn crockford_upper(bytes: &[u8]) -> String {
base32(bytes, CROCKFORD)
}
pub fn claim_node_id(dk: &[u8; 32]) -> String {
format!("n_{}", &base32_lower(dk)[..26])
}
pub fn random_id(prefix: &str, bytes: &[u8; 16]) -> String {
format!("{prefix}_{}", &base32_lower(bytes)[..26])
}
pub fn new_random_id(prefix: &str) -> Result<String, crate::CloudError> {
let mut bytes = [0u8; 16];
getrandom::fill(&mut bytes).map_err(|e| crate::CloudError::Local(format!("random: {e}")))?;
Ok(random_id(prefix, &bytes))
}
pub fn event_id(wall_ms: u64, random: &[u8; 10]) -> String {
let mut n: u128 = u128::from(wall_ms & 0xffff_ffff_ffff) << 80;
for (i, b) in random.iter().enumerate() {
n |= u128::from(*b) << (8 * (9 - i));
}
(0..26)
.rev()
.map(|i| CROCKFORD[((n >> (5 * i)) & 31) as usize] as char)
.collect()
}
pub fn new_event_id(wall_ms: u64) -> Result<String, crate::CloudError> {
let mut random = [0u8; 10];
getrandom::fill(&mut random).map_err(|e| crate::CloudError::Local(format!("random: {e}")))?;
Ok(event_id(wall_ms, &random))
}
pub fn legacy_conversion_event_id(pk_id: &[u8; 32], revision: u64, item_key: &str) -> String {
let mut h = blake3::Hasher::new_keyed(pk_id);
h.update(b"conv");
h.update(&revision.to_be_bytes());
h.update(item_key.as_bytes());
crockford_upper(h.finalize().as_bytes())[..26].to_string()
}