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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use std::ops;
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Span<T> {
start: Location,
end: Location,
value: T,
}
impl<T> Span<T> {
pub fn new(start: Location, end: Location, value: T) -> Span<T> {
Span { start, end, value }
}
pub fn start(&self) -> Location {
self.start
}
pub fn end(&self) -> Location {
self.end
}
pub fn value_ref(&self) -> &T {
&self.value
}
pub fn extend(&mut self, end: Location) {
self.end = end;
}
pub fn into_inner(self) -> (Location, T, Location) {
(self.start, self.value, self.end)
}
}
impl From<(usize, char)> for Span<char> {
fn from((pos, value): (usize, char)) -> Self {
Self::new(pos.into(), (pos + value.len_utf8() - 1).into(), value)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Default)]
pub struct Location(usize);
impl Location {
pub fn new(location: usize) -> Location {
Location(location)
}
}
impl ops::AddAssign<usize> for Location {
fn add_assign(&mut self, rhs: usize) {
self.0 += rhs;
}
}
impl ops::Add<usize> for Location {
type Output = Location;
fn add(mut self, rhs: usize) -> Location {
self += rhs;
self
}
}
impl From<usize> for Location {
fn from(value: usize) -> Self {
Self::new(value)
}
}
#[cfg(test)]
mod test {
use std::usize;
use super::*;
#[test]
fn location_default_eq_location_0() {
let sut: Location = Default::default();
assert_eq!(sut, Location::new(0));
}
#[test]
fn location_add_eq_usize_add() {
let base = 5;
let inc = 3;
let sut = Location::new(base);
assert_eq!(sut + inc, Location::new(base + inc));
}
#[test]
#[should_panic]
fn location_add_overflow_panics() {
Location::new(usize::max_value()) + 3;
}
#[test]
fn span_from_usize_char_gives_expected_result_for_euro_sign() {
let value = '€';
let pos = 5;
let sut: Span<char> = (pos, value).into();
assert_eq!(sut, Span::new(pos.into(), (pos + 3 - 1).into(), value));
}
#[test]
fn span_from_usize_char_give_expected_result_for_a() {
let value = 'a';
let pos = 0;
let sut: Span<char> = (pos, value).into();
assert_eq!(sut, Span::new(pos.into(), pos.into(), value));
}
}