trifid/trifid-api/src/id.rs

41 lines
1.1 KiB
Rust
Raw Normal View History

2023-11-19 15:49:08 +00:00
use rand::Rng;
pub const ID_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
pub const ID_RAND_LEN: u32 = 26;
2023-11-21 01:07:02 +00:00
pub const TOKEN_CHARSET: &[u8] =
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
2023-11-19 15:49:08 +00:00
pub const TOKEN_RAND_LEN: u32 = 43;
#[macro_export]
macro_rules! randid {
(id) => {
$crate::id::random_with_charset($crate::id::ID_RAND_LEN, $crate::id::ID_CHARSET)
};
(id $p:expr) => {
2023-11-21 01:07:02 +00:00
format!(
"{}-{}",
$p,
$crate::id::random_with_charset($crate::id::ID_RAND_LEN, $crate::id::ID_CHARSET)
)
2023-11-19 15:49:08 +00:00
};
(token) => {
random_with_charset($crate::id::TOKEN_RAND_LEN, $crate::id::TOKEN_CHARSET)
};
(token $p:expr) => {
2023-11-21 01:07:02 +00:00
format!(
"{}-{}",
$p,
$crate::id::random_with_charset($crate::id::TOKEN_RAND_LEN, $crate::id::TOKEN_CHARSET)
)
2023-11-19 15:49:08 +00:00
};
}
pub fn random_with_charset(len: u32, charset: &[u8]) -> String {
(0..len)
.map(|_| {
let idx = rand::thread_rng().gen_range(0..charset.len());
charset[idx] as char
})
.collect()
2023-11-21 01:07:02 +00:00
}