Cotton code
94 lines · 2.8 KB · RustRaw
//! Record ids. The schema's ids are UUID-shaped TEXT (they came from Postgres//! that way), so new rows keep minting v4s.//!//! There is no entropy policy here: this crate takes its randomness from the//! caller (spec R7). Hand it sixteen bytes and it sets the version and variant//! bits and formats them./// A UUID v4 from sixteen caller-supplied bytes.////// Bits 4–7 of octet 6 become `0100` (version 4) and bits 6–7 of octet 8/// become `10` (the RFC 4122 variant), exactly as the TypeScript does — so a/// caller handing over sixteen zero bytes still gets a WELL-SHAPED v4, which/// is what the shape assertions in `ids.test.ts` check.pub fn format_uuid_v4(bytes: &[u8; 16]) -> String {    let mut b = *bytes;    b[6] = (b[6] & 0x0f) | 0x40;    b[8] = (b[8] & 0x3f) | 0x80;    let hex = |slice: &[u8]| -> String { slice.iter().map(|byte| format!("{byte:02x}")).collect() };    format!(        "{}-{}-{}-{}-{}",        hex(&b[0..4]),        hex(&b[4..6]),        hex(&b[6..8]),        hex(&b[8..10]),        hex(&b[10..16])    )}#[cfg(test)]mod tests {    use super::*;    fn is_v4_shaped(id: &str) -> bool {        let groups: Vec<&str> = id.split('-').collect();        groups.len() == 5            && [8, 4, 4, 4, 12]                == [                    groups[0].len(),                    groups[1].len(),                    groups[2].len(),                    groups[3].len(),                    groups[4].len(),                ]            && id                .chars()                .all(|c| c == '-' || c.is_ascii_digit() || ('a'..='f').contains(&c))            && groups[2].starts_with('4')            && matches!(groups[3].as_bytes()[0], b'8' | b'9' | b'a' | b'b')    }    #[test]    fn mints_rfc_4122_v4_shaped_ids() {        for seed in 0u8..=255 {            let bytes = [seed; 16];            let id = format_uuid_v4(&bytes);            assert!(is_v4_shaped(&id), "{id} from byte {seed}");        }    }    #[test]    fn all_zero_bytes_still_carry_the_version_and_variant() {        assert_eq!(            format_uuid_v4(&[0; 16]),            "00000000-0000-4000-8000-000000000000"        );    }    #[test]    fn all_one_bytes_keep_every_other_bit() {        assert_eq!(            format_uuid_v4(&[0xff; 16]),            "ffffffff-ffff-4fff-bfff-ffffffffffff"        );    }    #[test]    fn the_bytes_land_where_the_typescript_puts_them() {        let bytes: [u8; 16] = [            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,            0xee, 0xff,        ];        assert_eq!(            format_uuid_v4(&bytes),            "00112233-4455-4677-8899-aabbccddeeff"        );    }    #[test]    fn different_bytes_give_different_ids() {        let a = format_uuid_v4(&[1; 16]);        let b = format_uuid_v4(&[2; 16]);        assert_ne!(a, b);    }}