| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
use serde::{Deserialize, Serialize}; |
| 13 |
use uuid::Uuid; |
| 14 |
|
| 15 |
macro_rules! uuid_id { |
| 16 |
($name:ident, $doc:literal) => { |
| 17 |
#[doc = $doc] |
| 18 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 19 |
#[serde(transparent)] |
| 20 |
pub struct $name(pub Uuid); |
| 21 |
|
| 22 |
impl From<Uuid> for $name { |
| 23 |
fn from(id: Uuid) -> Self { |
| 24 |
Self(id) |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
impl From<$name> for Uuid { |
| 29 |
fn from(id: $name) -> Self { |
| 30 |
id.0 |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
impl std::fmt::Display for $name { |
| 35 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 36 |
self.0.fmt(f) |
| 37 |
} |
| 38 |
} |
| 39 |
}; |
| 40 |
} |
| 41 |
|
| 42 |
uuid_id!( |
| 43 |
RoomId, |
| 44 |
"A chat room. One per community in Multithreaded; one per stream in MNW." |
| 45 |
); |
| 46 |
uuid_id!( |
| 47 |
UserId, |
| 48 |
"A chat participant, in the host app's user namespace." |
| 49 |
); |
| 50 |
|
| 51 |
|
| 52 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] |
| 53 |
#[serde(transparent)] |
| 54 |
pub struct MessageId(pub i64); |
| 55 |
|
| 56 |
impl std::fmt::Display for MessageId { |
| 57 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 58 |
self.0.fmt(f) |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 68 |
#[serde(transparent)] |
| 69 |
pub struct Nonce(pub String); |
| 70 |
|
| 71 |
impl Nonce { |
| 72 |
|
| 73 |
|
| 74 |
pub const MAX_LEN: usize = 64; |
| 75 |
|
| 76 |
|
| 77 |
pub fn parse(raw: impl Into<String>) -> Option<Self> { |
| 78 |
let raw = raw.into(); |
| 79 |
(!raw.is_empty() && raw.len() <= Self::MAX_LEN).then_some(Self(raw)) |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
#[cfg(test)] |
| 84 |
mod tests { |
| 85 |
use super::*; |
| 86 |
|
| 87 |
#[test] |
| 88 |
fn nonce_rejects_empty_and_overlong() { |
| 89 |
assert!(Nonce::parse("").is_none()); |
| 90 |
assert!(Nonce::parse("a").is_some()); |
| 91 |
assert!(Nonce::parse("x".repeat(Nonce::MAX_LEN)).is_some()); |
| 92 |
assert!(Nonce::parse("x".repeat(Nonce::MAX_LEN + 1)).is_none()); |
| 93 |
} |
| 94 |
|
| 95 |
#[test] |
| 96 |
fn message_ids_order_by_value() { |
| 97 |
assert!(MessageId(1) < MessageId(2)); |
| 98 |
} |
| 99 |
} |
| 100 |
|