| 1 |
use crate::Uuid; |
| 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_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)] |
| 39 |
mod tests { |
| 40 |
use super::*; |
| 41 |
use crate::{Variant, Version}; |
| 42 |
|
| 43 |
#[cfg(target_arch = "wasm32")] |
| 44 |
use wasm_bindgen_test::*; |
| 45 |
|
| 46 |
#[test] |
| 47 |
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] |
| 48 |
fn test_new() { |
| 49 |
let uuid = Uuid::new_v4(); |
| 50 |
|
| 51 |
assert_eq!(uuid.get_version(), Some(Version::Random)); |
| 52 |
assert_eq!(uuid.get_variant(), Variant::RFC4122); |
| 53 |
} |
| 54 |
|
| 55 |
#[test] |
| 56 |
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] |
| 57 |
fn test_get_version() { |
| 58 |
let uuid = Uuid::new_v4(); |
| 59 |
|
| 60 |
assert_eq!(uuid.get_version(), Some(Version::Random)); |
| 61 |
assert_eq!(uuid.get_version_num(), 4) |
| 62 |
} |
| 63 |
} |