Cotton code
47 lines · 1.9 KB · RustRaw
//! A SHORT REFERENCE FOR ANY RECORD (transform, contract 1; architect, 22 Oct//! 2026): four characters of Crockford base32 a person can read out or type//! back ("7KQ2"), stable for the id. It takes an id and nothing else — never a//! table, never a column — and returns a typed [`ShortRef`]; the words around//! it ("#7KQ2") are the `ident` line set's.//!//! The four characters are the first twenty bits of the SHA-256 of the id,//! never digits read off the id: four decimal digits collide within a few//! hundred records, and twenty hashed bits (1,048,576 refs) keep a list of a//! few thousand records almost entirely apart. A ref is a handle for a person,//! not a key: two records may share one, and nothing looks a record up by it.use sha2::{Digest, Sha256};/// Crockford's base32 alphabet: digits and capitals without I, L, O and U,/// so nothing reads as another character or spells a word by accident.pub const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";/// How many characters a ref has.pub const LENGTH: usize = 4;/// A record's short reference, its four Crockford characters.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]pub struct ShortRef([u8; LENGTH]);impl ShortRef {    /// The four characters, uppercase.    pub fn as_str(&self) -> &str {        std::str::from_utf8(&self.0).expect("the alphabet is ASCII")    }}/// The short reference of `id`: the same id always gives the same ref.pub fn short_ref(id: &str) -> ShortRef {    let digest = Sha256::digest(id.as_bytes());    let bits = (u32::from(digest[0]) << 12) | (u32::from(digest[1]) << 4) | (u32::from(digest[2]) >> 4);    let mut chars = [0_u8; LENGTH];    for (place, char) in chars.iter_mut().enumerate() {        let shift = 5 * (LENGTH - 1 - place);        *char = ALPHABET[((bits >> shift) & 0x1f) as usize];    }    ShortRef(chars)}#[cfg(test)]#[path = "short_ref_tests.rs"]mod tests;