Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v1: get node_id automatically #740

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ macro-diagnostics = ["dep:uuid-macro-internal"]
# NOTE: When adding new features, check the `ci.yml` workflow
# and include them where necessary (you can follow along with existing features)
v1 = ["atomic"]
v1_auto = ["v1", "dep:mac_address", "rng", "std"]
v3 = ["md5"]
v4 = ["rng"]
v5 = ["sha1"]
Expand All @@ -77,6 +78,10 @@ atomic = ["dep:atomic"]

borsh = ["dep:borsh", "dep:borsh-derive"]

[dependencies]
mac_address = { version = "1.1.5", optional = true }


# Public: Used in trait impls on `Uuid`
[dependencies.bytemuck]
version = "1.14.0"
Expand Down
23 changes: 23 additions & 0 deletions benches/v1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#![feature(test)]

extern crate test;

use test::Bencher;

#[cfg(feature = "v1")]
#[bench]
fn bench_v1(b: &mut Bencher) {
b.iter(|| {
let node_id: [u8; 6] = [1, 2, 3, 4, 5, 6];
let uuid = uuid::Uuid::now_v1(&node_id);
})
}

#[cfg(feature = "v1_auto")]
#[bench]
fn bench_v1_auto(b: &mut Bencher) {
let uuid = uuid::Uuid::now_v1_auto();
b.iter(|| {
let uuid = uuid::Uuid::now_v1_auto();
})
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@ pub use timestamp::context::Context;
// Soft-deprecated (Rust doesn't support deprecating re-exports)
// Use `Context` from the crate root instead
pub mod v1;
#[cfg(feature="v1_auto")]
mod node_id;
#[cfg(feature = "v3")]
mod v3;
#[cfg(feature = "v4")]
Expand Down
31 changes: 31 additions & 0 deletions src/node_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::sync::OnceLock;

static NODE_ID: OnceLock<[u8; 6]> = OnceLock::new();

pub(crate) fn get_or_make_node_id() -> &'static [u8; 6] {
NODE_ID.get_or_init(|| match mac_address::get_mac_address() {
Ok(Some(mac)) => mac.bytes(),
_ => make_random_node_id(),
})
}

fn make_random_node_id() -> [u8; 6] {
let mut rand_bytes = [0u8; 6];

crate::rng::fill_random_bytes(&mut rand_bytes);

// set multicast bit
rand_bytes[0] = rand_bytes[0] | 0x01;
rand_bytes
}

#[cfg(test)]
mod tests {

#[test]
fn test_multicast_bit_set() {
// non deterministic test
let node1 = super::make_random_node_id();
assert_eq!(node1[0] & 0x01, 1);
}
}
17 changes: 17 additions & 0 deletions src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,20 @@ pub(crate) fn u16() -> u16 {
rand::random()
}
}

#[cfg(feature = "v1_auto")]
pub(crate) fn fill_random_bytes(buf: &mut [u8]) {
#[cfg(not(feature = "fast-rng"))]
{
getrandom::getrandom(buf).unwrap_or_else(|err| {
// NB: getrandom::Error has no source; this is adequate display
panic!("could not retrieve random bytes for node id: {}", err)
});
}

#[cfg(feature = "fast-rng")]
{
use rand::RngCore;
rand::thread_rng().fill_bytes(buf);
}
}
29 changes: 29 additions & 0 deletions src/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ impl Uuid {
Self::new_v1(ts, node_id)
}

/// Create a new version 1 UUID using the current system time and node ID.
///
/// This method fully automates constructing a version 1 UUID, with no additional arguments required.
/// Use it to get a v1 UUID based on RFC 4122 semantics.
///
/// To specify `node_id` manually, use [`Uuid::now_v1`] instead.
///
/// Note that usage of this method requires the `v1_auto` feature of this crate
/// to be enabled.
#[cfg(feature = "v1_auto")]
pub fn now_v1_auto() -> Self {
let ts = Timestamp::now(crate::timestamp::context::shared_context());
let node_id = super::node_id::get_or_make_node_id();
Self::new_v1(ts, node_id)
}

/// Create a new version 1 UUID using the given timestamp and node ID.
///
/// Also see [`Uuid::now_v1`] for a convenient way to generate version 1
Expand Down Expand Up @@ -197,4 +213,17 @@ mod tests {
assert_eq!(uuid3.get_timestamp().unwrap().to_rfc4122().1, 1);
assert_eq!(uuid4.get_timestamp().unwrap().to_rfc4122().1, 2);
}

#[cfg(feature = "v1_auto")]
#[test]
fn test_v1_auto() {
use crate::node_id::get_or_make_node_id;

let node1 = get_or_make_node_id();
let node2 = get_or_make_node_id();
let node3 = get_or_make_node_id();
assert_eq!(node1, node2);
assert_eq!(node2, node3);
println!("{:x?}", &node1);
}
}