uuid/
v4.rs

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    /// * [UUID Version 4 in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-5.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        // This is an optimized method for generating random UUIDs that just masks
35        // out the bits for the version and variant and sets them both together
36        Uuid::from_u128(
37            crate::rng::u128() & 0xFFFFFFFFFFFF4FFFBFFFFFFFFFFFFFFF | 0x40008000000000000000,
38        )
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use crate::{Variant, Version};
46
47    #[cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))]
48    use wasm_bindgen_test::*;
49
50    #[test]
51    #[cfg_attr(
52        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
53        wasm_bindgen_test
54    )]
55    fn test_new() {
56        let uuid = Uuid::new_v4();
57
58        assert_eq!(uuid.get_version(), Some(Version::Random));
59        assert_eq!(uuid.get_variant(), Variant::RFC4122);
60    }
61
62    #[test]
63    #[cfg_attr(
64        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
65        wasm_bindgen_test
66    )]
67    fn test_get_version() {
68        let uuid = Uuid::new_v4();
69
70        assert_eq!(uuid.get_version(), Some(Version::Random));
71        assert_eq!(uuid.get_version_num(), 4)
72    }
73}