1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::{fmt, hash};
use uuid::Uuid;
/// Unique identifier for an event, backed by a UUID v4.
///
/// Every [`Envelope`](crate::Envelope) is assigned an `EventId` at creation time.
/// IDs are random (not monotonic) - use [`Meta::timestamp()`](crate::Meta::timestamp)
/// for ordering.
///
/// `EventId` is `Copy` and cheap to pass around. Use [`Display`](std::fmt::Display)
/// to get the UUID string representation, or [`as_u128()`](Self::as_u128) for the raw `u128`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, hash::Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct EventId(u128);
impl EventId {
/// Generate a new random event ID (UUID v4).
#[must_use]
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self(Uuid::new_v4().as_u128())
}
/// Returns the raw `u128` value.
pub fn as_u128(&self) -> u128 {
self.0
}
/// Returns the ID as a [`Uuid`].
pub fn to_uuid(&self) -> Uuid {
Uuid::from_u128(self.0)
}
}
impl From<u128> for EventId {
fn from(value: u128) -> Self {
EventId(value)
}
}
impl From<EventId> for u128 {
fn from(value: EventId) -> Self {
value.0
}
}
impl fmt::Display for EventId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_uuid())
}
}