|
| 1 | +use bencher_valid::BASE_36; |
| 2 | +use uuid::Uuid; |
| 3 | + |
| 4 | +pub fn encode_uuid(uuid: Uuid) -> String { |
| 5 | + const ENCODED_LEN: usize = 13; |
| 6 | + |
| 7 | + let base = BASE_36.len() as u64; |
| 8 | + let chars = BASE_36.chars().collect::<Vec<_>>(); |
| 9 | + |
| 10 | + let (lhs, rhs) = uuid.as_u64_pair(); |
| 11 | + let mut num = hash_combined(lhs, rhs); |
| 12 | + |
| 13 | + let mut result = String::new(); |
| 14 | + while num > 0 { |
| 15 | + #[allow(clippy::cast_possible_truncation)] |
| 16 | + let remainder = (num % base) as usize; |
| 17 | + if let Some(c) = chars.get(remainder) { |
| 18 | + result.push(*c); |
| 19 | + } |
| 20 | + num /= base; |
| 21 | + } |
| 22 | + |
| 23 | + result |
| 24 | + .chars() |
| 25 | + .chain(std::iter::repeat('0')) |
| 26 | + .take(ENCODED_LEN) |
| 27 | + .collect() |
| 28 | +} |
| 29 | + |
| 30 | +// https://stackoverflow.com/a/27952689 |
| 31 | +// https://www.boost.org/doc/libs/1_43_0/doc/html/hash/reference.html#boost.hash_combine |
| 32 | +#[allow(clippy::unreadable_literal)] |
| 33 | +const GOLDEN_RATIO: u64 = 0x9e3779b97f4a7c15; |
| 34 | +fn hash_combined(lhs: u64, rhs: u64) -> u64 { |
| 35 | + lhs ^ (rhs |
| 36 | + .wrapping_add(GOLDEN_RATIO) |
| 37 | + .wrapping_add(lhs << 6) |
| 38 | + .wrapping_add(lhs >> 2)) |
| 39 | +} |
| 40 | + |
| 41 | +#[cfg(test)] |
| 42 | +mod tests { |
| 43 | + use super::*; |
| 44 | + use uuid::Uuid; |
| 45 | + |
| 46 | + #[test] |
| 47 | + fn test_encode_uuid() { |
| 48 | + let uuid = Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(); |
| 49 | + assert_eq!(encode_uuid(uuid), "p78ezm4408me2"); |
| 50 | + |
| 51 | + let uuid = Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").unwrap(); |
| 52 | + assert_eq!(encode_uuid(uuid), "gf47mznnithi0"); |
| 53 | + |
| 54 | + let uuid = Uuid::parse_str("12345678-1234-5678-1234-567812345678").unwrap(); |
| 55 | + assert_eq!(encode_uuid(uuid), "nfi03cu0p7x71"); |
| 56 | + } |
| 57 | +} |
0 commit comments