Skip to main content

simraft_core/
ids.rs

1//! Identifier and index newtypes shared by every simraft-core module.
2//!
3//! All identifiers are plain `u64` wrappers. They carry no behavior beyond
4//! ordering, formatting, and the small amount of arithmetic the protocol
5//! performs on terms and log indexes, so that raw integers never mix
6//! domains (a term is never silently used as an index).
7
8use core::fmt;
9
10/// A virtual time value in ticks, supplied by the driver.
11///
12/// The core never reads a wall clock. One tick is one virtual millisecond
13/// by convention; the protocol only ever compares ticks against deadlines
14/// it computed itself.
15pub type Tick = u64;
16
17/// Identifies one node in the cluster.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
19pub struct NodeId(pub u64);
20
21impl fmt::Display for NodeId {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        write!(f, "n{}", self.0)
24    }
25}
26
27/// Identifies one client session. Chosen by the client at session start.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
29pub struct ClientId(pub u64);
30
31impl fmt::Display for ClientId {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(f, "c{}", self.0)
34    }
35}
36
37/// A Raft term: a monotonically increasing logical clock value.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
39pub struct Term(pub u64);
40
41impl Term {
42    /// The term before any election has happened.
43    pub const ZERO: Self = Self(0);
44
45    /// The next term.
46    #[must_use]
47    pub const fn next(self) -> Self {
48        Self(self.0 + 1)
49    }
50}
51
52impl fmt::Display for Term {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(f, "term {}", self.0)
55    }
56}
57
58/// A position in the replicated log. Index 0 is the sentinel empty entry;
59/// the first real entry is index 1.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
61pub struct LogIndex(pub u64);
62
63impl LogIndex {
64    /// The sentinel index before the first real entry.
65    pub const ZERO: Self = Self(0);
66
67    /// The next index.
68    #[must_use]
69    pub const fn next(self) -> Self {
70        Self(self.0 + 1)
71    }
72}
73
74impl fmt::Display for LogIndex {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(f, "index {}", self.0)
77    }
78}