Skip to content

Instantly share code, notes, and snippets.

@only-cliches
Last active March 2, 2020 06:00
Show Gist options
  • Save only-cliches/76d867bc1af7ee81a3abb07cd8b8d842 to your computer and use it in GitHub Desktop.
Save only-cliches/76d867bc1af7ee81a3abb07cd8b8d842 to your computer and use it in GitHub Desktop.
UUID v4 in Rust
use rand::Rng;
fn calc_uuid() -> String {
let mut result: String = "".to_owned();
let mut rng = rand::thread_rng();
for x in 0..16 {
let rand_value = if x == 6 {
64 + rng.gen_range(0, 15)
} else {
rng.gen_range(0, 255)
} as u64;
if x == 4 || x == 6 || x == 8 || x == 10 {
result.push_str("-");
}
result.push_str(to_hex(rand_value, 2).as_str());
}
result
}
fn to_hex(num: u64, length: i32) -> String {
let mut result: String = "".to_owned();
let hex_values = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
let mut i = length as i32 - 1;
while i >= 0 {
let raise = (16u32).pow(i as u32) as f64;
let index = (num as f64 / raise).floor() as u32;
result.push_str(hex_values[(index % 16u32) as usize]);
i -= 1;
}
result
}
fn main() {
// generate 50 uuids
for _x in 0..50 {
println!("{}", calc_uuid());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment