feat(serial):基本完成UUID和Short UUID的生成功能。
This commit is contained in:
@@ -3,3 +3,46 @@ pub mod uuid {
|
||||
Box::from(uuid::Uuid::new_v4().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub mod short_uuid {
|
||||
const STR_SRC: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
|
||||
pub fn new(length: i16) -> Box<String> {
|
||||
let length = if length < 2 {
|
||||
2
|
||||
} else if length > 128 {
|
||||
128
|
||||
} else {
|
||||
length
|
||||
};
|
||||
let choices = STR_SRC.as_bytes();
|
||||
let mut uuid = uuid::Uuid::new_v4().as_u128();
|
||||
let mut mask = 0_u128;
|
||||
let mut result_bits: Vec<i64> = Vec::new();
|
||||
let (mask_length, last_mask_length) = if 128 % length == 0 {
|
||||
(128 / length, 0)
|
||||
} else {
|
||||
(128 / length + 1, 128 / length - 128 % length)
|
||||
};
|
||||
for _ in 1..mask_length {
|
||||
mask = (mask << 1) | 0b1;
|
||||
}
|
||||
if last_mask_length > 0 {
|
||||
let mut last_mask = 0_u128;
|
||||
for _ in 1..last_mask_length {
|
||||
last_mask = (last_mask << 1) | 0b1;
|
||||
}
|
||||
result_bits.push(((uuid & last_mask) as i64) % choices.len() as i64);
|
||||
uuid = uuid >> last_mask_length;
|
||||
}
|
||||
for _ in 0..(length - if last_mask_length > 0 { 1 } else { 0 }) {
|
||||
result_bits.push(((uuid & mask) as i64) % choices.len() as i64);
|
||||
uuid = uuid >> mask_length;
|
||||
}
|
||||
let mut code: Vec<String> = Vec::new();
|
||||
result_bits.reverse();
|
||||
for i in result_bits {
|
||||
code.push(String::from_utf8(vec![choices[i as usize]]).unwrap());
|
||||
}
|
||||
Box::from(code.join(""))
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user