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    /// [`getrandom`]: https://crates.io/crates/getrandom
28    /// [from_random_bytes]: struct.Builder.html#method.from_random_bytes
29    pub fn new_v4() -> Uuid {
30        crate::Builder::from_random_bytes(crate::rng::bytes()).into_uuid()
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    use crate::{Variant, Version};
39
40    #[cfg(target_arch = "wasm32")]
41    use wasm_bindgen_test::*;
42
43    #[test]
44    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
45    fn test_new() {
46        let uuid = Uuid::new_v4();
47
48        assert_eq!(uuid.get_version(), Some(Version::Random));
49        assert_eq!(uuid.get_variant(), Variant::RFC4122);
50    }
51
52    #[test]
53    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
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}