forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_utils.rs
More file actions
372 lines (323 loc) · 11.2 KB
/
string_utils.rs
File metadata and controls
372 lines (323 loc) · 11.2 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use serde::{
Deserialize,
Serialize,
};
/// Iterate over the lines in `buf` and include line endings in the results.
/// Also, provide byte offsets of line beginnings and endings.
pub fn lines_with_endings(buf: &str) -> impl Iterator<Item = (&str, usize, usize)> {
let mut rest = buf;
let mut rest_offset = 0;
std::iter::from_fn(move || match rest.find('\n') {
Some(i) => {
let start = rest_offset;
let end = i + 1;
let line = &rest[..end];
rest = &rest[end..];
rest_offset += end;
Some((line, start, rest_offset))
}
None if !rest.is_empty() => {
let start = rest_offset;
let end = rest.len();
let line = rest;
rest = &rest[end..];
rest_offset += end;
Some((line, start, rest_offset))
}
None => None,
})
}
/// Strip the characters in the string `strip` from the left side of the string
/// slice `input`.
pub fn lstrip_slice<'a>(input: &'a str, strip: &str) -> &'a str {
let mut start = 0;
for c in input.chars() {
if strip.contains(c) {
start += c.len_utf8();
} else {
break;
}
}
&input[start..]
}
/// Strip the characters in the string `strip` from the right side of the string
/// slice `input`.
pub fn rstrip_slice<'a>(input: &'a str, strip: &str) -> &'a str {
let mut end = input.len();
for (i, c) in input.char_indices().rev() {
if strip.contains(c) {
end = i;
} else {
break;
}
}
&input[..end]
}
/// A position in a source file specified by a 1-indexed line number and a
/// 0-indexed byte offset into the line specified by that number.
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
pub struct Position {
/// A 1-indexed line number
pub line: usize,
/// A 0-indexed byte offset into a line
pub col: usize,
}
impl Position {
fn new(line: usize, col: usize) -> Self {
Position { line, col }
}
}
/// Efficiently find the text positions (line, column tuples) of a monotonically
/// increasing sequence of byte offsets in a string. Non-monotonic sequences
/// are also supported but are less efficient.
pub struct StringPositions<'a> {
/// A string in which text positions should be calculated
input: &'a str,
/// The 1-indexed line number at the current byte offset
line: usize,
/// The 0-indexed column number at the current byte offset
col: usize,
/// The current byte offset
offset: usize,
}
impl<'a> StringPositions<'a> {
/// Create a new position counter over the string in `input`.
pub fn new(input: &'a str) -> Self {
Self {
input,
line: 1,
col: 0,
offset: 0,
}
}
/// Reset the position counter's internal state.
fn reset(&mut self) {
self.line = 1;
self.col = 0;
self.offset = 0;
}
/// Get the position at byte offset `pos_offset` in a string.
pub fn get_pos(&mut self, pos_offset: usize) -> Option<Position> {
if pos_offset >= self.input.len() {
// Position does not exist
return None;
}
if pos_offset < self.offset {
// The desired position is behind the current cursor. Start from the beginning.
self.reset()
}
let rel_offset = pos_offset - self.offset;
let rest = &self.input[self.offset..];
for (chr_offset, chr) in rest.char_indices() {
if chr_offset >= rel_offset {
break;
}
let chr_len = chr.len_utf8();
if chr == '\n' {
self.line += 1;
self.col = 0;
} else {
self.col += chr_len;
}
self.offset += chr_len;
}
Some(Position::new(self.line, self.col))
}
/// Get the last valid position in a string.
pub fn get_last(&mut self) -> Option<Position> {
let len = self.input.len();
if len == 0 {
None
} else {
self.get_pos(len - 1)
}
}
/// Get the pseudo-position representing the end of the file (string).
pub fn get_eof(&mut self) -> Position {
match self.get_last() {
None => Position::new(1, 0),
Some(last_pos) => {
let last_chr = self.input[self.offset..].chars().next().unwrap();
if last_chr == '\n' {
Position::new(last_pos.line + 1, 0)
} else {
Position::new(last_pos.line, last_pos.col + 1)
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lines_with_endings() {
// Empty string
let input = r"";
let actual: Vec<_> = lines_with_endings(input).collect();
let expected: Vec<(&'static str, usize, usize)> = Vec::new();
assert_eq!(actual, expected);
// Single line
let input = r"testing";
let actual: Vec<_> = lines_with_endings(input).collect();
let expected = vec![("testing", 0, 7)];
assert_eq!(actual, expected);
// No newline at start or end
let input = r"testing
the
lines
here";
let actual: Vec<_> = lines_with_endings(input).collect();
let expected = vec![
("testing\n", 0, 8),
("the\n", 8, 12),
("lines \n", 12, 19),
("here", 19, 23),
];
assert_eq!(actual, expected);
// Newline at start only
let input = r"
testing
the
lines
here";
let actual: Vec<_> = lines_with_endings(input).collect();
let expected = vec![
("\n", 0, 1),
("testing\n", 1, 9),
("the\n", 9, 13),
("lines \n", 13, 20),
("here", 20, 24),
];
assert_eq!(actual, expected);
// Newline at end only
let input = r"testing
the
lines
here
";
let actual: Vec<_> = lines_with_endings(input).collect();
let expected = vec![
("testing\n", 0, 8),
("the\n", 8, 12),
("lines \n", 12, 19),
("here\n", 19, 24),
];
assert_eq!(actual, expected);
// Newline at start and end
let input = r"
testing
the
lines
here
";
let actual: Vec<_> = lines_with_endings(input).collect();
let expected = vec![
("\n", 0, 1),
("\n", 1, 2),
("testing\n", 2, 10),
("\n", 10, 11),
("the\n", 11, 15),
("lines \n", 15, 22),
("here\n", 22, 27),
("\n", 27, 28),
("\n", 28, 29),
];
assert_eq!(actual, expected);
}
#[test]
fn test_lstrip_slice() {
let examples = vec![
(("\r\nasdfasdf", "\r\n"), "asdfasdf"),
(("\n\rasdfasdf", "\n"), "\rasdfasdf"),
(("\r\nasdfasdf", ""), "\r\nasdfasdf"),
(("asdfasdf", "\r\n"), "asdfasdf"),
(("", "\r\n"), ""),
];
for ((input, strip), expected) in examples {
let actual = lstrip_slice(input, strip);
assert_eq!(actual, expected);
}
}
#[test]
fn test_rstrip_slice() {
let examples = vec![
(("asdfasdf\r\n", "\r\n"), "asdfasdf"),
(("asdfasdf\r\n", "\n"), "asdfasdf\r"),
(("asdfasdf\r\n", ""), "asdfasdf\r\n"),
(("asdfasdf", "\r\n"), "asdfasdf"),
(("", "\r\n"), ""),
];
for ((input, strip), expected) in examples {
let actual = rstrip_slice(input, strip);
assert_eq!(actual, expected);
}
}
#[test]
fn test_file_positions() {
// Empty string has expected behavior
let mut string_pos = StringPositions::new(&r#""#);
assert_eq!(string_pos.get_pos(0), None);
assert_eq!(string_pos.get_pos(1), None);
assert_eq!(string_pos.get_last(), None);
assert_eq!(string_pos.get_eof(), Position::new(1, 0));
// Can get same position twice
let mut string_pos = StringPositions::new(&r#"asdf"#);
assert_eq!(string_pos.get_pos(0), Some(Position::new(1, 0)));
assert_eq!(string_pos.get_pos(0), Some(Position::new(1, 0)));
assert_eq!(string_pos.get_pos(1), Some(Position::new(1, 1)));
assert_eq!(string_pos.get_pos(1), Some(Position::new(1, 1)));
assert_eq!(string_pos.get_last(), Some(Position::new(1, 3)));
assert_eq!(string_pos.get_eof(), Position::new(1, 4));
// Can get sequential positions
let mut string_pos = StringPositions::new(&r#"asdf"#);
assert_eq!(string_pos.get_pos(0), Some(Position::new(1, 0)));
assert_eq!(string_pos.get_pos(1), Some(Position::new(1, 1)));
assert_eq!(string_pos.get_pos(2), Some(Position::new(1, 2)));
assert_eq!(string_pos.get_pos(3), Some(Position::new(1, 3)));
// Can get non-sequential positions
let mut string_pos = StringPositions::new(&r#"asdf"#);
assert_eq!(string_pos.get_pos(0), Some(Position::new(1, 0)));
assert_eq!(string_pos.get_pos(1), Some(Position::new(1, 1)));
assert_eq!(string_pos.get_pos(0), Some(Position::new(1, 0)));
// Can get sequential then invalid
let mut string_pos = StringPositions::new(&r#"asdf"#);
assert_eq!(string_pos.get_pos(0), Some(Position::new(1, 0)));
assert_eq!(string_pos.get_pos(1), Some(Position::new(1, 1)));
assert_eq!(string_pos.get_pos(2), Some(Position::new(1, 2)));
assert_eq!(string_pos.get_pos(3), Some(Position::new(1, 3)));
assert_eq!(string_pos.get_pos(4), None);
assert_eq!(string_pos.get_pos(5), None);
// Can get invalid
let mut string_pos = StringPositions::new(&r#"asdf"#);
assert_eq!(string_pos.get_pos(4), None);
// Can get multiple line positions
let mut string_pos = StringPositions::new(
&r#"i wrote this
thing that finds
positions on lines"#,
);
assert_eq!(string_pos.get_pos(4), Some(Position::new(1, 4)));
assert_eq!(string_pos.get_pos(11), Some(Position::new(1, 11)));
assert_eq!(string_pos.get_pos(12), Some(Position::new(1, 12)));
assert_eq!(string_pos.get_pos(13), Some(Position::new(2, 0)));
assert_eq!(string_pos.get_pos(18), Some(Position::new(2, 5)));
assert_eq!(string_pos.get_pos(28), Some(Position::new(2, 15)));
assert_eq!(string_pos.get_pos(29), Some(Position::new(2, 16)));
assert_eq!(string_pos.get_pos(30), Some(Position::new(3, 0)));
assert_eq!(string_pos.get_pos(42), Some(Position::new(3, 12)));
assert_eq!(string_pos.get_pos(47), Some(Position::new(3, 17)));
assert_eq!(string_pos.get_pos(48), None);
assert_eq!(string_pos.get_last(), Some(Position::new(3, 17)));
assert_eq!(string_pos.get_eof(), Position::new(3, 18));
// EOF is after newline
let mut string_pos = StringPositions::new(
&r#"i wrote this
thing that finds
positions on lines
"#,
);
assert_eq!(string_pos.get_last(), Some(Position::new(3, 18)));
assert_eq!(string_pos.get_eof(), Position::new(4, 0));
}
}