1#![cfg(feature = "rnd")]
2
3use crate::{Layout, Variant, Version, UUID};
4
5use rand;
6
7impl UUID {
8 #[cfg(feature = "rand")]
10 pub fn v4() -> Layout {
11 let rng = rand::random::<u128>();
12 let rand = rng.to_be_bytes();
13 Layout {
14 field_low: ((rand[0] as u32) << 24)
15 | (rand[1] as u32) << 16
16 | (rand[2] as u32) << 8
17 | rand[3] as u32,
18 field_mid: (rand[4] as u16) << 8 | (rand[5] as u16),
19 field_high_and_version: ((rand[6] as u16) << 8 | (rand[7] as u16)) & 0xfff
20 | (Version::RAND as u16) << 12,
21 clock_seq_high_and_reserved: (rand[8] & 0xf) | (Variant::RFC as u8) << 4,
22 clock_seq_low: rand[9] as u8,
23 node: [rand[10], rand[11], rand[12], rand[13], rand[14], rand[15]],
24 }
25 }
26}
27
28#[macro_export]
30macro_rules! v4 {
31 () => {
32 format!("{}", $crate::UUID::v4().as_bytes())
33 };
34 (expr:lower) => {
35 format!("{}", $crate::UUID::v4().as_bytes().to_lower())
36 };
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 #[cfg(feature = "rand")]
44 #[test]
45 fn test_v4() {
46 let uuid = UUID::v4();
47 assert_eq!(uuid.get_version(), Some(Version::RAND));
48 assert_eq!(uuid.get_variant(), Some(Variant::RFC));
49 }
50}