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
123
124
125
126
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Location {
pub(super) row: u32,
pub(super) column: u32,
}
impl Default for Location {
fn default() -> Self {
Self { row: 1, column: 0 }
}
}
impl Location {
pub fn fmt_with(
&self,
f: &mut std::fmt::Formatter,
e: &impl std::fmt::Display,
) -> std::fmt::Result {
write!(f, "{} at line {} column {}", e, self.row(), self.column())
}
}
impl Location {
pub fn new(row: usize, column: usize) -> Self {
let row = row.try_into().expect("Location::row over u32");
let column = column.try_into().expect("Location::column over u32");
Location { row, column }
}
pub fn row(&self) -> usize {
self.row as usize
}
pub fn column(&self) -> usize {
self.column as usize
}
pub fn reset(&mut self) {
self.row = 1;
self.column = 0;
}
pub fn go_right(&mut self) {
self.column += 1;
}
pub fn go_left(&mut self) {
self.column -= 1;
}
pub fn newline(&mut self) {
self.row += 1;
self.column = 0;
}
pub fn with_col_offset<T: TryInto<isize>>(&self, offset: T) -> Self
where
<T as TryInto<isize>>::Error: std::fmt::Debug,
{
let column = (self.column as isize
+ offset
.try_into()
.expect("offset should be able to convert to isize")) as u32;
Self {
row: self.row,
column,
}
}
pub fn with_row_offset<T: TryInto<isize>>(&self, offset: T) -> Self
where
<T as TryInto<isize>>::Error: std::fmt::Debug,
{
let row = (self.row as isize
+ offset
.try_into()
.expect("offset should be able to convert to isize")) as u32;
Self {
row,
column: self.column,
}
}
}
#[cfg(test)]
mod tests {
use crate::Location;
#[test]
fn test_gt() {
assert!(Location::new(1, 2) > Location::new(1, 1));
assert!(Location::new(2, 1) > Location::new(1, 1));
assert!(Location::new(2, 1) > Location::new(1, 2));
}
#[test]
fn test_lt() {
assert!(Location::new(1, 1) < Location::new(1, 2));
assert!(Location::new(1, 1) < Location::new(2, 1));
assert!(Location::new(1, 2) < Location::new(2, 1));
}
#[test]
fn test_with_col_offset() {
assert_eq!(Location::new(1, 1).with_col_offset(1), Location::new(1, 2));
assert_eq!(Location::new(1, 1).with_col_offset(-1), Location::new(1, 0));
}
#[test]
fn test_with_row_offset() {
assert_eq!(Location::new(1, 1).with_row_offset(1), Location::new(2, 1));
assert_eq!(Location::new(1, 1).with_row_offset(-1), Location::new(0, 1));
}
}