foundationdb/recipes/ranked_register/
types.rs1use std::fmt;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
28pub struct Rank(u64);
29
30impl Rank {
31 pub const ZERO: Rank = Rank(0);
33
34 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug"))]
39 pub fn new(process_id: u32, sequence: u32) -> Self {
40 Self(((sequence as u64) << 32) | process_id as u64)
41 }
42
43 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
45 pub fn process_id(&self) -> u32 {
46 self.0 as u32
47 }
48
49 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
51 pub fn sequence(&self) -> u32 {
52 (self.0 >> 32) as u32
53 }
54
55 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
57 pub fn as_u64(&self) -> u64 {
58 self.0
59 }
60}
61
62impl From<u64> for Rank {
63 fn from(value: u64) -> Self {
64 Self(value)
65 }
66}
67
68impl fmt::Display for Rank {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 write!(
71 f,
72 "Rank(seq={}, pid={})",
73 self.sequence(),
74 self.process_id()
75 )
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Default)]
85pub struct RegisterState {
86 pub(crate) max_read_rank: Rank,
87 pub(crate) max_write_rank: Rank,
88 pub(crate) value: Option<Vec<u8>>,
89}
90
91impl RegisterState {
92 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
94 pub fn max_read_rank(&self) -> Rank {
95 self.max_read_rank
96 }
97
98 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
100 pub fn max_write_rank(&self) -> Rank {
101 self.max_write_rank
102 }
103
104 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
106 pub fn value(&self) -> Option<&[u8]> {
107 self.value.as_deref()
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct ReadResult {
118 pub(crate) write_rank: Rank,
119 pub(crate) value: Option<Vec<u8>>,
120}
121
122impl ReadResult {
123 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
125 pub fn write_rank(&self) -> Rank {
126 self.write_rank
127 }
128
129 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
131 pub fn value(&self) -> Option<&[u8]> {
132 self.value.as_deref()
133 }
134
135 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
137 pub fn into_value(self) -> Option<Vec<u8>> {
138 self.value
139 }
140}
141
142#[must_use = "a committed write result controls whether co-staged application writes are valid"]
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum WriteResult {
146 Committed,
148 Aborted,
150}
151
152impl WriteResult {
153 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
155 pub fn is_committed(&self) -> bool {
156 matches!(self, WriteResult::Committed)
157 }
158}