1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PositionKind {
Absolute,
Relative,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Position {
pub line: usize,
pub column: usize,
pub kind: PositionKind,
}
impl Position {
pub fn abs(line: usize, column: usize) -> Self {
Position { line, column, kind: PositionKind::Absolute }
}
pub fn rel(line: usize, column: usize) -> Self {
Position { line, column, kind: PositionKind::Relative }
}
pub fn subposition(&self, line: usize, column: usize) -> Self {
let column = if line == 1 {
self.column + column - 1
} else {
column
};
let line = self.line + line - 1;
Self { line, column, kind: self.kind }
}
}
impl std::fmt::Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "line: {} column: {}", self.line, self.column)
}
}
#[cfg(test)]
mod tests {
use super::Position;
use super::PositionKind;
#[test]
fn subpositions() {
let p = Position { line: 2, column: 3, kind: PositionKind::Absolute };
let sub = p.subposition(1, 1);
assert_eq!(sub, p);
let sub = p.subposition(1, 5);
assert_eq!(sub, Position { line: 2, column: 7, kind: PositionKind::Absolute });
let sub = p.subposition(4, 5);
assert_eq!(sub, Position { line: 5, column: 5, kind: PositionKind::Absolute });
let p = Position { kind: PositionKind::Relative, ..p };
let sub = p.subposition(1, 1);
assert_eq!(sub, p);
}
}