pub fn short_id(len: usize) -> String {
let hex = uuid::Uuid::new_v4().simple().to_string();
hex[..len.min(hex.len())].to_string()
}
pub fn alnum_id(len: usize) -> String {
const ALPHABET: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
let mut out = String::with_capacity(len);
while out.len() < len {
for b in uuid::Uuid::new_v4().into_bytes() {
out.push(ALPHABET[(b as usize) % ALPHABET.len()] as char);
if out.len() == len {
break;
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_id_has_requested_length_and_is_hex() {
for n in [6, 10, 12, 16, 20, 32] {
let id = short_id(n);
assert_eq!(id.len(), n);
assert!(id
.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
}
}
#[test]
fn short_id_clamps_over_32() {
assert_eq!(short_id(64).len(), 32);
}
#[test]
fn alnum_id_has_requested_length_and_is_base36() {
for n in [1, 26, 40] {
let id = alnum_id(n);
assert_eq!(id.len(), n);
assert!(id
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
}
}
}