Skip to main content

tephra_types/
position.rs

1use std::{fmt, ops};
2
3#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
4pub struct Position(pub(crate) u64);
5
6impl Position {
7    pub const ZERO: Position = Position(0);
8
9    /// The largest representable position, the dual of [`ZERO`](Self::ZERO). Used as the
10    /// "from the tip" sentinel for a backwards read: `read_back(query, Position::MAX, limit)`
11    /// starts at the current durable tip, since the read is always clamped to the pinned
12    /// watermark anyway.
13    pub const MAX: Position = Position(u64::MAX);
14
15    pub fn new(n: u64) -> Self {
16        Position(n)
17    }
18
19    pub fn get(self) -> u64 {
20        self.0
21    }
22
23    pub fn next(self) -> Position {
24        Position(self.0 + 1)
25    }
26
27    pub fn offset_from(self, base: Position) -> u64 {
28        self - base
29    }
30}
31
32impl From<u64> for Position {
33    fn from(n: u64) -> Self {
34        Position(n)
35    }
36}
37
38impl ops::Add<Position> for Position {
39    type Output = u64;
40
41    fn add(self, rhs: Position) -> Self::Output {
42        self.0.add(rhs.0)
43    }
44}
45
46impl ops::Add<u64> for Position {
47    type Output = u64;
48
49    fn add(self, rhs: u64) -> Self::Output {
50        self.0.add(rhs)
51    }
52}
53
54impl ops::Add<Position> for u64 {
55    type Output = u64;
56
57    fn add(self, rhs: Position) -> Self::Output {
58        self.add(rhs.0)
59    }
60}
61
62impl ops::Sub<Position> for Position {
63    type Output = u64;
64
65    fn sub(self, rhs: Position) -> Self::Output {
66        self.0.sub(rhs.0)
67    }
68}
69
70impl ops::Sub<u64> for Position {
71    type Output = u64;
72
73    fn sub(self, rhs: u64) -> Self::Output {
74        self.0.sub(rhs)
75    }
76}
77
78impl ops::Sub<Position> for u64 {
79    type Output = u64;
80
81    fn sub(self, rhs: Position) -> Self::Output {
82        self.sub(rhs.0)
83    }
84}
85
86impl fmt::Display for Position {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        self.0.fmt(f)
89    }
90}