use core::{fmt, marker::PhantomData};
use crate::metadata::{SchemaRevision, WireMajor};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct EventId(u128);
impl EventId {
const OFFSET: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
#[must_use]
pub const fn from_name(name: &str) -> Self {
let bytes = name.as_bytes();
let mut hash = Self::OFFSET;
let mut index = 0;
while index < bytes.len() {
hash = (hash ^ bytes[index] as u128).wrapping_mul(Self::PRIME);
index += 1;
}
Self(hash)
}
#[must_use]
pub const fn as_u128(self) -> u128 {
self.0
}
#[must_use]
pub const fn from_u128(value: u128) -> Self {
Self(value)
}
}
impl fmt::Debug for EventId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_tuple("EventId").field(&self.0).finish()
}
}
impl fmt::Display for EventId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:032x}", self.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Delivery {
#[default]
Ordered,
Latest,
}
impl Delivery {
pub(crate) fn follows(self, previous: u64, next: u64) -> bool {
match self {
Self::Ordered => previous.checked_add(1) == Some(next),
Self::Latest => next > previous,
}
}
}
pub trait EventSpec {
type Payload;
const ID: EventId;
const WIRE_MAJOR: WireMajor = WireMajor(1);
const SCHEMA_REVISION: SchemaRevision = SchemaRevision(1);
const DELIVERY: Delivery = Delivery::Ordered;
}
pub struct EventValue<E: EventSpec> {
payload: E::Payload,
marker: PhantomData<fn() -> E>,
}
impl<E: EventSpec> EventValue<E> {
#[must_use]
pub const fn new(payload: E::Payload) -> Self {
Self {
payload,
marker: PhantomData,
}
}
#[must_use]
pub fn into_inner(self) -> E::Payload {
self.payload
}
}
impl<E> Clone for EventValue<E>
where
E: EventSpec,
E::Payload: Clone,
{
fn clone(&self) -> Self {
Self::new(self.payload.clone())
}
}
impl<E> Copy for EventValue<E>
where
E: EventSpec,
E::Payload: Copy,
{
}
impl<E> fmt::Debug for EventValue<E>
where
E: EventSpec,
E::Payload: fmt::Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("EventValue")
.field(&self.payload)
.finish()
}
}
impl<E> PartialEq for EventValue<E>
where
E: EventSpec,
E::Payload: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.payload == other.payload
}
}
impl<E> Eq for EventValue<E>
where
E: EventSpec,
E::Payload: Eq,
{
}