| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
use serde::{Deserialize, Serialize}; |
| 16 |
use std::fmt; |
| 17 |
use uuid::Uuid; |
| 18 |
|
| 19 |
macro_rules! id_newtype { |
| 20 |
($(#[$doc:meta])* $name:ident) => { |
| 21 |
$(#[$doc])* |
| 22 |
#[derive( |
| 23 |
Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, |
| 24 |
)] |
| 25 |
#[serde(transparent)] |
| 26 |
pub struct $name(pub Uuid); |
| 27 |
|
| 28 |
impl $name { |
| 29 |
|
| 30 |
pub const fn new(id: Uuid) -> Self { |
| 31 |
Self(id) |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
pub const fn as_uuid(self) -> Uuid { |
| 37 |
self.0 |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
pub const fn nil() -> Self { |
| 44 |
Self(Uuid::nil()) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
impl From<Uuid> for $name { |
| 49 |
fn from(id: Uuid) -> Self { |
| 50 |
Self(id) |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
impl From<$name> for Uuid { |
| 55 |
fn from(value: $name) -> Self { |
| 56 |
value.0 |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
impl fmt::Display for $name { |
| 61 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 62 |
fmt::Display::fmt(&self.0, f) |
| 63 |
} |
| 64 |
} |
| 65 |
}; |
| 66 |
} |
| 67 |
|
| 68 |
id_newtype!( |
| 69 |
|
| 70 |
DeviceId |
| 71 |
); |
| 72 |
id_newtype!( |
| 73 |
|
| 74 |
UserId |
| 75 |
); |
| 76 |
id_newtype!( |
| 77 |
|
| 78 |
AppId |
| 79 |
); |
| 80 |
id_newtype!( |
| 81 |
|
| 82 |
|
| 83 |
GroupId |
| 84 |
); |
| 85 |
|
| 86 |
#[cfg(test)] |
| 87 |
mod tests { |
| 88 |
use super::*; |
| 89 |
|
| 90 |
#[test] |
| 91 |
fn serde_is_transparent_to_uuid() { |
| 92 |
let raw = Uuid::from_u128(0x1234); |
| 93 |
let id = DeviceId::new(raw); |
| 94 |
|
| 95 |
assert_eq!( |
| 96 |
serde_json::to_string(&id).unwrap(), |
| 97 |
serde_json::to_string(&raw).unwrap() |
| 98 |
); |
| 99 |
|
| 100 |
let back: DeviceId = serde_json::from_str(&serde_json::to_string(&raw).unwrap()).unwrap(); |
| 101 |
assert_eq!(back, id); |
| 102 |
} |
| 103 |
|
| 104 |
#[test] |
| 105 |
fn conversions_round_trip() { |
| 106 |
let raw = Uuid::from_u128(7); |
| 107 |
assert_eq!(Uuid::from(AppId::from(raw)), raw); |
| 108 |
assert_eq!(UserId::new(raw).as_uuid(), raw); |
| 109 |
} |
| 110 |
|
| 111 |
#[test] |
| 112 |
fn distinct_types_do_not_unify() { |
| 113 |
|
| 114 |
|
| 115 |
let raw = Uuid::from_u128(0xabcd); |
| 116 |
assert_eq!(DeviceId::new(raw).to_string(), raw.to_string()); |
| 117 |
} |
| 118 |
} |
| 119 |
|