fader_master/core/src/revision.rs

76 lines
2.0 KiB
Rust

/// Monotonic revision of domain-visible state.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Revision(u64);
impl Revision {
/// Initial revision before any accepted state change.
pub const INITIAL: Self = Self(0);
/// Creates a revision from its persisted/wire representation.
#[must_use]
pub const fn new(value: u64) -> Self {
Self(value)
}
/// Returns the numeric wire representation.
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
/// Advances the revision, returning `None` rather than wrapping.
#[must_use]
pub const fn checked_next(self) -> Option<Self> {
match self.0.checked_add(1) {
Some(next) => Some(Self(next)),
None => None,
}
}
}
/// Connection generation used to reject events from an obsolete backend.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct BackendEpoch(u64);
impl BackendEpoch {
/// Initial epoch before the first connection is established.
pub const INITIAL: Self = Self(0);
/// Creates an epoch from its numeric representation.
#[must_use]
pub const fn new(value: u64) -> Self {
Self(value)
}
/// Returns the numeric representation.
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
/// Advances the epoch, returning `None` rather than wrapping.
#[must_use]
pub const fn checked_next(self) -> Option<Self> {
match self.0.checked_add(1) {
Some(next) => Some(Self(next)),
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counters_advance_without_wrapping() {
assert_eq!(Revision::INITIAL.checked_next(), Some(Revision::new(1)));
assert_eq!(Revision::new(u64::MAX).checked_next(), None);
assert_eq!(
BackendEpoch::INITIAL.checked_next(),
Some(BackendEpoch::new(1))
);
assert_eq!(BackendEpoch::new(u64::MAX).checked_next(), None);
}
}