| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::fmt; |
| 8 | |
| 9 | use uuid::Uuid; |
| 10 | |
| 11 | |
| 12 | macro_rules! typed_id { |
| 13 | ($(#[$meta:meta])* $name:ident) => { |
| 14 | $(#[$meta])* |
| 15 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 16 | pub struct $name(String); |
| 17 | |
| 18 | impl $name { |
| 19 | |
| 20 | pub fn generate() -> Self { |
| 21 | Self(Uuid::new_v4().to_string()) |
| 22 | } |
| 23 | |
| 24 | |
| 25 | pub fn from_trusted(value: impl Into<String>) -> Self { |
| 26 | Self(value.into()) |
| 27 | } |
| 28 | |
| 29 | pub fn as_str(&self) -> &str { |
| 30 | &self.0 |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl fmt::Display for $name { |
| 35 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 36 | f.write_str(&self.0) |
| 37 | } |
| 38 | } |
| 39 | }; |
| 40 | } |
| 41 | |
| 42 | typed_id!( |
| 43 | |
| 44 | UserId |
| 45 | ); |
| 46 | |
| 47 | typed_id!( |
| 48 | |
| 49 | OrgId |
| 50 | ); |
| 51 | |
| 52 | typed_id!( |
| 53 | |
| 54 | MembershipId |
| 55 | ); |
| 56 | |
| 57 | typed_id!( |
| 58 | |
| 59 | RepoId |
| 60 | ); |
| 61 | |
| 62 | #[cfg(test)] |
| 63 | mod tests { |
| 64 | use super::*; |
| 65 | |
| 66 | #[test] |
| 67 | fn generated_ids_are_unique() { |
| 68 | assert_ne!(UserId::generate(), UserId::generate()); |
| 69 | } |
| 70 | |
| 71 | #[test] |
| 72 | fn round_trips_through_str() { |
| 73 | let id = UserId::from_trusted("user-1"); |
| 74 | |
| 75 | assert_eq!(id.as_str(), "user-1"); |
| 76 | assert_eq!(id.to_string(), "user-1"); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | typed_id!( |
| 81 | |
| 82 | TokenId |
| 83 | ); |
| 84 | |
| 85 | typed_id!( |
| 86 | |
| 87 | IssueId |
| 88 | ); |
| 89 | |
| 90 | typed_id!( |
| 91 | |
| 92 | IssueCommentId |
| 93 | ); |
| 94 | |
| 95 | typed_id!( |
| 96 | |
| 97 | PushEventId |
| 98 | ); |
| 99 | |
| 100 | typed_id!( |
| 101 | |
| 102 | WebhookId |
| 103 | ); |
| 104 | |
| 105 | typed_id!( |
| 106 | |
| 107 | WebhookDeliveryId |
| 108 | ); |
| 109 | |
| 110 | typed_id!( |
| 111 | |
| 112 | LabelId |
| 113 | ); |
| 114 | |
| 115 | typed_id!( |
| 116 | |
| 117 | PullRequestId |
| 118 | ); |
| 119 | |
| 120 | typed_id!( |
| 121 | |
| 122 | PullRequestCommentId |
| 123 | ); |