Skip to content

Instantly share code, notes, and snippets.

@i-hardy
Last active April 24, 2020 08:30
Show Gist options
  • Save i-hardy/69a98692817dfb796182a8e897240837 to your computer and use it in GitHub Desktop.
Save i-hardy/69a98692817dfb796182a8e897240837 to your computer and use it in GitHub Desktop.
Generating UUIDs in Rust
extern crate hex;
extern crate rand;
use rand::Rng;
fn create_byte_vector() -> Vec<u8> {
let mut random_bytes = rand::thread_rng().gen::<[u8; 16]>();
random_bytes[6] = (random_bytes[6] & 0x0f) | 0x40;
random_bytes[8] = (random_bytes[8] & 0x3f) | 0x80;
random_bytes.to_vec()
}
fn hex_encode(byte_vector: Vec<u8>) -> Vec<String> {
byte_vector
.into_iter()
.map(|byte| hex::encode([byte]))
.collect()
}
fn main() {
let hex_vector = hex_encode(create_byte_vector());
let mut uuid = String::new();
for (index, byte) in hex_vector.iter().enumerate() {
uuid.push_str(byte);
if [3, 5, 7, 9].contains(&index) {
uuid.push('-');
}
}
println!("{:?}", uuid);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment