3 releases
0.1.2 | Oct 10, 2021 |
---|---|
0.1.1 | Oct 10, 2021 |
0.1.0 | Oct 10, 2021 |
#2316 in Procedural macros
11KB
compiled-uuid
Anywhere you're building Uuid
s from a string literal, you should use uuid
.
Motivation
If you want to use a fixed Uuid
throughout your program and avoid parsing it multiple times, often you might use lazy_static
to cache the Uuid
after parsing the first time:
lazy_static! {
pub static ref MY_UUID: Uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
}
However, this method introduces overhead through parsing and unwrap
ping at runtime.
uuid
, on the other hand, provides a zero-cost runtime solution:
const MY_UUID: Uuid = uuid!("550e8400-e29b-41d4-a716-446655440000");
Usage
compiled_uuid
exposes one macro called uuid
, which parses Uuid
s at compile time. On success, it resolves to Uuid::from_bytes
, which cannot fail and has zero runtime cost.
When you write this:
let id: Uuid = uuid!("F9168C5E-CEB2-4FAA-B6BF-329BF39FA1E4");
It expands to this:
let id: Uuid = ::uuid::Uuid::from_bytes([
249u8, 22u8, 140u8, 94u8, 206u8, 178u8, 79u8, 170u8, 182u8, 191u8, 50u8, 155u8, 243u8,
159u8, 161u8, 228u8,
]);
If the UUID cannot be parsed successfully:
let id: Uuid = uuid!("F9168C5E-ZEB2-4FAA-B6BF-329BF39FA1E4");
Then a compilation error is raised:
error: invalid character: expected an optional prefix of `urn:uuid:` followed by 0123456789abcdefABCDEF-, found Z at 9
|
| let id: Uuid = uuid!("F9168C5E-ZEB2-4FAA-B6BF-329BF39FA1E4");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
License
compiled-uuid
is open-source software, distributed under the MIT license.
Dependencies
~0.5–1MB
~20K SLoC