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
155
156
157
158
159
160
161
162
use std::fmt;
use {
Stream,
};
#[must_use]
#[derive(PartialEq, Clone, Copy)]
pub struct StrSpan<'a> {
text: &'a str,
start: usize,
end: usize,
}
impl<'a> From<&'a str> for StrSpan<'a> {
fn from(text: &'a str) -> Self {
StrSpan {
text,
start: 0,
end: text.len(),
}
}
}
impl<'a> StrSpan<'a> {
pub fn from_substr(text: &str, start: usize, end: usize) -> StrSpan {
debug_assert!(start <= end);
debug_assert!(text.is_char_boundary(start));
debug_assert!(text.is_char_boundary(end));
StrSpan { text, start, end }
}
pub fn start(&self) -> usize {
self.start
}
pub fn end(&self) -> usize {
self.end
}
pub fn len(&self) -> usize {
self.end - self.start
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn full_len(&self) -> usize {
self.text.len()
}
pub fn to_str(&self) -> &'a str {
&self.text[self.start..self.end]
}
pub fn as_bytes(&self) -> &'a [u8] {
&self.text.as_bytes()[self.start..self.end]
}
pub fn slice_region(&self, start: usize, end: usize) -> StrSpan<'a> {
let start = self.start + start;
let end = self.start + end;
StrSpan::from_substr(self.text, start, end)
}
pub fn full_str(&self) -> &'a str {
self.text
}
pub fn trim(&self) -> StrSpan<'a> {
let mut s = Stream::from(*self);
s.skip_spaces();
let start = s.pos();
let mut end;
loop {
s.skip_bytes(|s, _| !s.starts_with_space());
end = s.pos();
s.skip_spaces();
if s.at_end() {
break;
}
}
self.slice_region(start, end)
}
}
impl<'a> fmt::Debug for StrSpan<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "StrSpan({:?} {}..{})", self.to_str(), self.start, self.end)
}
}
impl<'a> fmt::Display for StrSpan<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trim_1() {
assert_eq!(StrSpan::from(" text ").trim().to_str(), "text");
}
#[test]
fn trim_2() {
assert_eq!(StrSpan::from(" text text ").trim().to_str(), "text text");
}
#[test]
fn trim_3() {
assert_eq!(StrSpan::from(" text ").trim().to_str(), "text");
}
#[test]
fn trim_4() {
assert_eq!(StrSpan::from(" text text ").trim().to_str(), "text text");
}
#[test]
fn do_not_trim_1() {
assert_eq!(StrSpan::from("@textP").trim().to_str(), "@textP");
}
#[test]
fn do_not_trim_2() {
assert_eq!(StrSpan::from("&ref;text'").trim().to_str(), "&ref;text'");
}
}