Cotton code
216 lines · 7.8 KB · RustRaw
//! Op ids. Monotonic ULIDs so a batch written inside one millisecond still//! sorts in the order it was written — the outbox drains FIFO by op id, so a//! non-monotonic id would reorder a user's own edits against each other.//!//! The ENTROPY is the caller's (spec R7): nothing in this crate reads a random//! source, so `Monotonic::new` takes a fill function and the caller decides//! whether that is real crypto (the server, the Mac) or something weaker.use crate::error::{Result, StoreError};/// Crockford's base32 — no I, L, O or U, so a human reading an id aloud cannot/// produce a different one.const ENCODING: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";const TIME_LEN: usize = 10;const RANDOM_LEN: usize = 16;/// `32 ** 10 - 1` — the largest millisecond a 10-character time field holds.pub const MAX_TIME: i64 = 281_474_976_710_655;/// The time half of a ULID: `now_ms` in Crockford base32, ten characters, big/// endian so lexicographic order is chronological order.pub fn encode_time(now_ms: i64) -> Result<String> {    if !(0..=MAX_TIME).contains(&now_ms) {        return Err(StoreError::encode(format!(            "ulid timestamp out of range: {now_ms}"        )));    }    let mut indices = [0usize; TIME_LEN];    let mut remaining = now_ms;    for slot in indices.iter_mut().rev() {        *slot = (remaining % 32) as usize;        remaining /= 32;    }    Ok(indices        .into_iter()        .map(|index| ENCODING[index] as char)        .collect())}/// A ULID from a millisecond and sixteen caller-supplied bytes.////// Each byte picks one character of the alphabet. `newUlid` in TypeScript goes/// through `Math.floor(prng() * 32)` instead, which is the same uniform draw/// over the same alphabet — the ids are not expected to MATCH across the two/// implementations (they are random), only to have the same shape and the same/// order.pub fn new_ulid(now_ms: i64, randomness: &[u8; RANDOM_LEN]) -> Result<String> {    let mut out = encode_time(now_ms)?;    for byte in randomness {        out.push(ENCODING[usize::from(byte % 32)] as char);    }    Ok(out)}/// The monotonic factory: inside one millisecond the random half is/// INCREMENTED rather than redrawn, so a burst still sorts in write order.pub struct Monotonic<F: FnMut(&mut [u8])> {    seed: F,    last_time: i64,    last_random: [u8; RANDOM_LEN],}impl<F: FnMut(&mut [u8])> Monotonic<F> {    /// `seed` fills the slice it is handed with randomness. It is called once    /// per millisecond that produces an id — never inside this crate's own    /// code paths, which is what keeps the library free of an RNG.    pub fn new(seed: F) -> Self {        Monotonic {            seed,            last_time: 0,            last_random: [0; RANDOM_LEN],        }    }    /// The next id at `now_ms`.    ///    /// `now_ms <= last` holds the last millisecond and increments the random    /// half in base 32, carrying leftwards; an overflow of all sixteen    /// characters refuses rather than wrapping, exactly as the `ulid` package    /// does (it would otherwise emit an id that sorts before its predecessor).    pub fn next(&mut self, now_ms: i64) -> Result<String> {        if now_ms <= self.last_time {            self.increment_random()?;            return self.render(self.last_time);        }        if !(0..=MAX_TIME).contains(&now_ms) {            return Err(StoreError::encode(format!(                "ulid timestamp out of range: {now_ms}"            )));        }        self.last_time = now_ms;        let mut bytes = [0u8; RANDOM_LEN];        (self.seed)(&mut bytes);        for byte in bytes.iter_mut() {            *byte %= 32;        }        self.last_random = bytes;        self.render(now_ms)    }    fn render(&self, ms: i64) -> Result<String> {        let mut out = encode_time(ms)?;        for index in self.last_random {            out.push(ENCODING[usize::from(index)] as char);        }        Ok(out)    }    fn increment_random(&mut self) -> Result<()> {        for slot in self.last_random.iter_mut().rev() {            if *slot < 31 {                *slot += 1;                return Ok(());            }            *slot = 0;        }        Err(StoreError::encode(            "ulid: cannot increment the random component past its maximum",        ))    }}#[cfg(test)]mod tests {    use super::*;    /// A deterministic stand-in for the caller's randomness — no RNG in a test    /// either, so a failure is always reproducible.    fn counter_seed() -> impl FnMut(&mut [u8]) {        let mut tick = 0u8;        move |bytes: &mut [u8]| {            for byte in bytes.iter_mut() {                *byte = tick;                tick = tick.wrapping_add(7);            }        }    }    #[test]    fn is_twenty_six_crockford_characters() {        let id = new_ulid(1_700_000_000_000, &[0; 16]).expect("in range");        assert_eq!(id.len(), 26);        assert!(id.bytes().all(|b| ENCODING.contains(&b)), "{id}");    }    #[test]    fn the_time_half_is_the_millisecond_big_endian() {        assert_eq!(encode_time(0).expect("in range"), "0000000000");        assert_eq!(encode_time(1).expect("in range"), "0000000001");        assert_eq!(encode_time(32).expect("in range"), "0000000010");        // Pinned against the `ulid` package: encodeTime(1700000000000, 10).        assert_eq!(            encode_time(1_700_000_000_000).expect("in range"),            "01HF7YAT00"        );        assert_eq!(encode_time(MAX_TIME).expect("in range"), "7ZZZZZZZZZ");    }    #[test]    fn a_later_millisecond_always_sorts_later() {        let early = new_ulid(1_700_000_000_000, &[31; 16]).expect("in range");        let late = new_ulid(1_700_000_000_001, &[0; 16]).expect("in range");        assert!(late > early, "{late} !> {early}");    }    #[test]    fn refuses_a_millisecond_the_time_field_cannot_hold() {        assert!(encode_time(-1).is_err());        assert!(encode_time(MAX_TIME + 1).is_err());    }    #[test]    fn stays_monotonic_within_a_burst() {        let mut factory = Monotonic::new(counter_seed());        let ids: Vec<String> = (0..200)            .map(|_| factory.next(1_700_000_000_000).expect("in range"))            .collect();        let mut sorted = ids.clone();        sorted.sort();        assert_eq!(ids, sorted);        let unique: std::collections::BTreeSet<&String> = ids.iter().collect();        assert_eq!(unique.len(), 200);        for id in &ids {            assert_eq!(id.len(), 26);        }    }    #[test]    fn a_clock_that_stands_still_increments_rather_than_redraws() {        let mut factory = Monotonic::new(|bytes: &mut [u8]| bytes.fill(0));        let first = factory.next(1_700_000_000_000).expect("in range");        let second = factory.next(1_700_000_000_000).expect("in range");        assert_eq!(&first[..25], &second[..25]);        assert_eq!(&first[25..], "0");        assert_eq!(&second[25..], "1");    }    #[test]    fn a_clock_that_goes_backwards_still_moves_forwards() {        let mut factory = Monotonic::new(|bytes: &mut [u8]| bytes.fill(0));        let first = factory.next(1_700_000_000_000).expect("in range");        let after = factory.next(1_600_000_000_000).expect("in range");        assert!(after > first);        assert_eq!(&after[..TIME_LEN], &first[..TIME_LEN]);    }    #[test]    fn the_carry_walks_leftwards() {        let mut factory = Monotonic::new(|bytes: &mut [u8]| bytes.fill(31));        let first = factory.next(1_700_000_000_000).expect("in range");        assert_eq!(&first[TIME_LEN..], "ZZZZZZZZZZZZZZZZ");        // Every character is at its maximum, so the whole random half        // overflows and the factory refuses rather than wrapping to an id that        // sorts BEFORE the one it just gave out.        assert!(factory.next(1_700_000_000_000).is_err());    }}