1use crate::Uuid;
2
3impl 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_random_bytes`][from_random_bytes] function
11 /// instead.
12 ///
13 /// Note that usage of this method requires the `v4` feature of this crate
14 /// to be enabled.
15 ///
16 /// # Examples
17 ///
18 /// Basic usage:
19 ///
20 /// ```
21 /// # use uuid::{Uuid, Version};
22 /// let uuid = Uuid::new_v4();
23 ///
24 /// assert_eq!(Some(Version::Random), uuid.get_version());
25 /// ```
26 ///
27 /// # References
28 ///
29 /// * [Version 4 UUIDs in RFC4122](https://www.rfc-editor.org/rfc/rfc4122#section-4.4)
30 ///
31 /// [`getrandom`]: https://crates.io/crates/getrandom
32 /// [from_random_bytes]: struct.Builder.html#method.from_random_bytes
33 pub fn new_v4() -> Uuid {
34 crate::Builder::from_random_bytes(crate::rng::bytes()).into_uuid()
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41 use crate::{Variant, Version};
42
43 #[cfg(all(
44 target_arch = "wasm32",
45 target_vendor = "unknown",
46 target_os = "unknown"
47 ))]
48 use wasm_bindgen_test::*;
49
50 #[test]
51 #[cfg_attr(
52 all(
53 target_arch = "wasm32",
54 target_vendor = "unknown",
55 target_os = "unknown"
56 ),
57 wasm_bindgen_test
58 )]
59 fn test_new() {
60 let uuid = Uuid::new_v4();
61
62 assert_eq!(uuid.get_version(), Some(Version::Random));
63 assert_eq!(uuid.get_variant(), Variant::RFC4122);
64 }
65
66 #[test]
67 #[cfg_attr(
68 all(
69 target_arch = "wasm32",
70 target_vendor = "unknown",
71 target_os = "unknown"
72 ),
73 wasm_bindgen_test
74 )]
75 fn test_get_version() {
76 let uuid = Uuid::new_v4();
77
78 assert_eq!(uuid.get_version(), Some(Version::Random));
79 assert_eq!(uuid.get_version_num(), 4)
80 }
81}
82