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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use alloc::string::String;
use core::ops::Deref;
#[derive(Debug)]
pub struct SubStr<'a> {
target: &'a str,
start: usize,
end: usize,
inner: &'a str,
}
impl SubStr<'_> {
pub fn start(&self) -> usize {
self.start
}
pub fn end(&self) -> usize {
self.end
}
pub fn inner(&self) -> &str {
self.inner
}
}
impl Deref for SubStr<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.target
}
}
impl PartialEq<str> for SubStr<'_> {
fn eq(&self, other: &str) -> bool {
self.target == other
}
}
impl<'a> PartialEq<SubStr<'a>> for &str {
fn eq(&self, other: &SubStr<'a>) -> bool {
self == &other.target
}
}
impl PartialEq<String> for SubStr<'_> {
fn eq(&self, other: &String) -> bool {
self.target == other
}
}
impl<'a> PartialEq<SubStr<'a>> for String {
fn eq(&self, other: &SubStr<'a>) -> bool {
self == other.target
}
}
#[derive(Debug)]
pub struct SubStrIter<'a, S> where S: AsRef<str> {
src: &'a str,
src_index: usize,
start: S,
end: S,
}
impl<'a, S> SubStrIter<'a, S> where S: AsRef<str> {
fn new(source: &'a str, start: S, end: S) -> Self {
Self {
src: source,
src_index: 0,
start,
end,
}
}
}
impl<'a, S: AsRef<str>> Iterator for SubStrIter<'a, S> where S: AsRef<str> {
type Item = SubStr<'a>;
fn next(&mut self) -> Option<Self::Item> {
let start = self.start.as_ref();
let start_len = start.len();
let src = &self.src[self.src_index..];
if let Some(mut start_idx) = src.find(start) {
let end = self.end.as_ref();
let delta = start_idx + start_len;
if let Some(end_idx) = src[delta..].find(end) {
if start_len > 0 && end_idx > 0 {
if let Some(next_char_bytes) = src[start_idx..].chars().next().map(|c| c.len_utf8()) {
if let Some(next_start_idx) = src[start_idx + next_char_bytes .. delta + end_idx].rfind(start) {
start_idx += next_char_bytes + next_start_idx;
}
}
}
let end_len = end.len();
let end_idx = delta + end_idx + end_len;
let sub_start = self.src_index + start_idx;
self.src_index += end_idx;
let target = &src[start_idx..end_idx];
let inner = &target[start_len .. target.len() - end_len];
return Some(SubStr {
target,
start: sub_start,
end: self.src_index,
inner,
});
}
}
None
}
}
pub fn sub_strs<'a, S>(source: &'a str, start: S, end: S) -> SubStrIter<'a, S> where S: AsRef<str> {
SubStrIter::new(source, start, end)
}