laminar_connectors/postgres/cdc/lsn/
mod.rs1use std::fmt;
8use std::str::FromStr;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
20pub struct Lsn(u64);
21
22impl Lsn {
23 pub const ZERO: Lsn = Lsn(0);
25
26 pub const MAX: Lsn = Lsn(u64::MAX);
28
29 #[must_use]
31 pub const fn new(value: u64) -> Self {
32 Lsn(value)
33 }
34
35 #[must_use]
37 pub const fn as_u64(self) -> u64 {
38 self.0
39 }
40
41 #[must_use]
43 pub const fn segment(self) -> u32 {
44 let bytes = self.0.to_be_bytes();
45 u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
46 }
47
48 #[must_use]
50 pub const fn offset(self) -> u32 {
51 let bytes = self.0.to_be_bytes();
52 u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]])
53 }
54
55 #[must_use]
59 pub const fn diff(self, other: Lsn) -> u64 {
60 self.0.saturating_sub(other.0)
61 }
62
63 #[must_use]
65 pub const fn advance(self, bytes: u64) -> Lsn {
66 Lsn(self.0.saturating_add(bytes))
67 }
68
69 #[must_use]
71 pub const fn is_zero(self) -> bool {
72 self.0 == 0
73 }
74}
75
76impl fmt::Display for Lsn {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "{:X}/{:X}", self.segment(), self.offset())
79 }
80}
81
82impl FromStr for Lsn {
83 type Err = LsnParseError;
84
85 fn from_str(s: &str) -> Result<Self, Self::Err> {
86 let (high, low) = s
87 .split_once('/')
88 .ok_or_else(|| LsnParseError::InvalidFormat(s.to_string()))?;
89
90 let high = u32::from_str_radix(high, 16)
91 .map_err(|_| LsnParseError::InvalidHex(high.to_string()))?;
92 let low =
93 u32::from_str_radix(low, 16).map_err(|_| LsnParseError::InvalidHex(low.to_string()))?;
94
95 Ok(Lsn((u64::from(high) << 32) | u64::from(low)))
96 }
97}
98
99impl From<u64> for Lsn {
100 fn from(value: u64) -> Self {
101 Lsn(value)
102 }
103}
104
105impl From<Lsn> for u64 {
106 fn from(lsn: Lsn) -> Self {
107 lsn.0
108 }
109}
110
111#[derive(Debug, Clone, thiserror::Error)]
113pub enum LsnParseError {
114 #[error("invalid LSN format (expected X/Y): {0}")]
116 InvalidFormat(String),
117
118 #[error("invalid hex in LSN: {0}")]
120 InvalidHex(String),
121}
122
123#[cfg(test)]
124mod tests;