uuid/macros.rs
1/// Parse [`Uuid`][uuid::Uuid]s from string literals at compile time.
2///
3/// ## Usage
4///
5/// This macro transforms the string literal representation of a
6/// [`Uuid`][uuid::Uuid] into the bytes representation, raising a compilation
7/// error if it cannot properly be parsed.
8///
9/// ## Examples
10///
11/// Setting a global constant:
12///
13/// ```
14/// # use uuid::{uuid, Uuid};
15/// pub const SCHEMA_ATTR_CLASS: Uuid = uuid!("00000000-0000-0000-0000-ffff00000000");
16/// pub const SCHEMA_ATTR_UUID: Uuid = uuid!("00000000-0000-0000-0000-ffff00000001");
17/// pub const SCHEMA_ATTR_NAME: Uuid = uuid!("00000000-0000-0000-0000-ffff00000002");
18/// ```
19///
20/// Defining a local variable:
21///
22/// ```
23/// # use uuid::uuid;
24/// let uuid = uuid!("urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4");
25/// ```
26/// Using a const variable:
27/// ```
28/// # use uuid::uuid;
29/// const UUID_STR: &str = "12345678-1234-5678-1234-567812345678";
30/// let UUID = uuid!(UUID_STR);
31/// ```
32///
33/// [uuid::Uuid]: https://docs.rs/uuid/*/uuid/struct.Uuid.html
34#[macro_export]
35macro_rules! uuid {
36 ($uuid:expr) => {{
37 const OUTPUT: $crate::Uuid = match $crate::Uuid::try_parse($uuid) {
38 $crate::__macro_support::Ok(u) => u,
39 $crate::__macro_support::Err(_) => panic!("invalid UUID"),
40 };
41 OUTPUT
42 }};
43}
44
45// Internal macros
46
47// These `transmute` macros are a stepping stone towards `zerocopy` integration.
48// When the `zerocopy` feature is enabled, which it is in CI, the transmutes are
49// checked by it
50
51// SAFETY: Callers must ensure this call would be safe when handled by zerocopy
52#[cfg(not(all(uuid_unstable, feature = "zerocopy")))]
53macro_rules! unsafe_transmute_ref(
54 ($e:expr) => { unsafe { core::mem::transmute::<&_, &_>($e) } }
55);
56
57// SAFETY: Callers must ensure this call would be safe when handled by zerocopy
58#[cfg(all(uuid_unstable, feature = "zerocopy"))]
59macro_rules! unsafe_transmute_ref(
60 ($e:expr) => { zerocopy::transmute_ref!($e) }
61);
62
63// SAFETY: Callers must ensure this call would be safe when handled by zerocopy
64#[cfg(not(all(uuid_unstable, feature = "zerocopy")))]
65macro_rules! unsafe_transmute(
66 ($e:expr) => { unsafe { core::mem::transmute::<_, _>($e) } }
67);
68
69// SAFETY: Callers must ensure this call would be safe when handled by zerocopy
70#[cfg(all(uuid_unstable, feature = "zerocopy"))]
71macro_rules! unsafe_transmute(
72 ($e:expr) => { zerocopy::transmute!($e) }
73);