1 use crate::prelude::*; 2 3 impl Uuid { 4 /// Creates a random UUID. 5 /// 6 /// This uses the [`getrandom`] crate to utilise the operating system's RNG 7 /// as the source of random numbers. If you'd like to use a custom 8 /// generator, don't use this method: generate random bytes using your 9 /// custom generator and pass them to the 10 /// [`uuid::Builder::from_bytes`][from_bytes] function instead. 11 /// 12 /// Note that usage of this method requires the `v4` feature of this crate 13 /// to be enabled. 14 /// 15 /// # Examples 16 /// 17 /// Basic usage: 18 /// 19 /// ``` 20 /// use uuid::Uuid; 21 /// 22 /// let uuid = Uuid::new_v4(); 23 /// ``` 24 /// 25 /// [`getrandom`]: https://crates.io/crates/getrandom 26 /// [from_bytes]: struct.Builder.html#method.from_bytes new_v4() -> Uuid27 pub fn new_v4() -> Uuid { 28 let mut bytes = [0u8; 16]; 29 getrandom::getrandom(&mut bytes).unwrap_or_else(|err| { 30 // NB: getrandom::Error has no source; this is adequate display 31 panic!("could not retreive random bytes for uuid: {}", err) 32 }); 33 34 crate::Builder::from_bytes(bytes) 35 .set_variant(Variant::RFC4122) 36 .set_version(Version::Random) 37 .build() 38 } 39 } 40 41 #[cfg(test)] 42 mod tests { 43 use crate::prelude::*; 44 45 #[test] test_new()46 fn test_new() { 47 let uuid = Uuid::new_v4(); 48 49 assert_eq!(uuid.get_version(), Some(Version::Random)); 50 assert_eq!(uuid.get_variant(), Some(Variant::RFC4122)); 51 } 52 53 #[test] test_get_version()54 fn test_get_version() { 55 let uuid = Uuid::new_v4(); 56 57 assert_eq!(uuid.get_version(), Some(Version::Random)); 58 assert_eq!(uuid.get_version_num(), 4) 59 } 60 } 61