Debian Codegraph @

rust/hg-core/src/utils/strings.rs

raw
1 //! Contains string-related utilities.
2
3 use std::cell::Cell;
4 use std::fmt;
5 use std::io::Write as _;
6 use std::ops::Deref as _;
7
8 use crate::utils::hg_path::HgPath;
9
10 /// Useful until rust/issues/56345 is stable
11 ///
12 /// # Examples
13 ///
14 /// ```
15 /// use hg::utils::strings::find_slice_in_slice;
16 ///
17 /// let haystack = b"This is the haystack".to_vec();
18 /// assert_eq!(find_slice_in_slice(&haystack, b"the"), Some(8));
19 /// assert_eq!(find_slice_in_slice(&haystack, b"not here"), None);
20 /// ```
21 pub fn find_slice_in_slice<T>(slice: &[T], needle: &[T]) -> Option<usize>
22 where
23 for<'a> &'a [T]: PartialEq,
24 {
25 slice.windows(needle.len()).position(|window| window == needle)
26 }
27
28 /// Replaces the `from` slice with the `to` slice inside the `buf` slice.
29 /// `from` and `to` need to be of the exact same length, otherwise use
30 /// [`replace_slice`].
31 ///
32 /// # Panics
33 ///
34 /// Panics if `from` and `to` have different lengths.
35 ///
36 /// # Examples
37 ///
38 /// ```
39 /// use hg::utils::strings::replace_slice_exact;
40 ///
41 /// let mut line = b"I hate writing tests!".to_vec();
42 /// replace_slice_exact(&mut line, b"hate", b"love");
43 ///
44 /// assert_eq!(
45 /// line,
46 /// b"I love writing tests!".to_vec()
47 /// );
48 /// ```
49 ///
50 /// ```should_panic
51 /// use hg::utils::strings::replace_slice_exact;
52 ///
53 /// let mut line = b"I hate writing tests!".to_vec();
54 /// replace_slice_exact(&mut line, b"hate", b"enjoy");
55 /// ```
56 pub fn replace_slice_exact<T>(buf: &mut [T], from: &[T], to: &[T])
57 where
58 T: Clone + PartialEq,
59 {
60 assert_eq!(from.len(), to.len());
61 for i in 0..=buf.len() - from.len() {
62 if buf[i..].starts_with(from) {
63 buf[i..(i + from.len())].clone_from_slice(to);
64 }
65 }
66 }
67
68 /// Replaces every `from` slice with the `to` slice from `source` and returns
69 /// a [`Vec`].
70 /// For cases where `from` and `to` are the same length, use
71 /// [`replace_slice_exact`] for better performance.
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use hg::utils::strings::replace_slice;
77 ///
78 /// let line = b"I hate writing tests!".to_vec();
79 /// assert_eq!(
80 /// replace_slice(&line, b"hate", b"love"),
81 /// b"I love writing tests!".to_vec()
82 /// );
83 /// let line = b"I hate writing tests!".to_vec();
84 /// assert_eq!(
85 /// replace_slice(&line, b"hate", b"enjoy"),
86 /// b"I enjoy writing tests!".to_vec()
87 /// );
88 /// let line = b"I hate writing tests!".to_vec();
89 /// assert_eq!(
90 /// replace_slice(&line, b"hate", b"am"),
91 /// b"I am writing tests!".to_vec()
92 /// );
93 /// ```
94 pub fn replace_slice<T>(source: &[T], from: &[T], to: &[T]) -> Vec<T>
95 where
96 T: Clone + PartialEq,
97 {
98 let mut result = source.to_vec();
99 let from_len = from.len();
100 let to_len = to.len();
101
102 let mut i = 0;
103 while i + from_len <= result.len() {
104 if result[i..].starts_with(from) {
105 result.splice(i..i + from_len, to.iter().cloned());
106 i += to_len;
107 } else {
108 i += 1;
109 }
110 }
111
112 result
113 }
114
115 /// Returns the length of the common prefix of two strings.
116 pub fn common_prefix_length(xs: &[u8], ys: &[u8]) -> usize {
117 xs.iter().zip(ys).take_while(|(x, y)| x == y).count()
118 }
119
120 pub trait SliceExt {
121 fn trim_end(&self) -> &Self;
122 fn trim_start(&self) -> &Self;
123 fn trim_end_matches(&self, f: impl FnMut(u8) -> bool) -> &Self;
124 fn trim_start_matches(&self, f: impl FnMut(u8) -> bool) -> &Self;
125 fn trim(&self) -> &Self;
126 fn drop_prefix(&self, needle: &Self) -> Option<&Self>;
127 fn split_2(&self, separator: u8) -> Option<(&[u8], &[u8])>;
128 fn split_2_by_slice(&self, separator: &[u8]) -> Option<(&[u8], &[u8])>;
129 fn to_hex_bytes(&self) -> Vec<u8>;
130 }
131
132 impl SliceExt for [u8] {
133 fn trim_end(&self) -> &[u8] {
134 self.trim_end_matches(|byte| byte.is_ascii_whitespace())
135 }
136
137 fn trim_start(&self) -> &[u8] {
138 self.trim_start_matches(|byte| byte.is_ascii_whitespace())
139 }
140
141 fn trim_end_matches(&self, mut f: impl FnMut(u8) -> bool) -> &Self {
142 if let Some(last) = self.iter().rposition(|&byte| !f(byte)) {
143 &self[..=last]
144 } else {
145 &[]
146 }
147 }
148
149 fn trim_start_matches(&self, mut f: impl FnMut(u8) -> bool) -> &Self {
150 if let Some(first) = self.iter().position(|&byte| !f(byte)) {
151 &self[first..]
152 } else {
153 &[]
154 }
155 }
156
157 /// ```
158 /// use hg::utils::strings::SliceExt;
159 /// assert_eq!(
160 /// b" to trim ".trim(),
161 /// b"to trim"
162 /// );
163 /// assert_eq!(
164 /// b"to trim ".trim(),
165 /// b"to trim"
166 /// );
167 /// assert_eq!(
168 /// b" to trim".trim(),
169 /// b"to trim"
170 /// );
171 /// ```
172 fn trim(&self) -> &[u8] {
173 self.trim_start().trim_end()
174 }
175
176 fn drop_prefix(&self, needle: &Self) -> Option<&Self> {
177 if self.starts_with(needle) {
178 Some(&self[needle.len()..])
179 } else {
180 None
181 }
182 }
183
184 fn split_2(&self, separator: u8) -> Option<(&[u8], &[u8])> {
185 let pos = memchr::memchr(separator, self)?;
186 Some((&self[..pos], &self[pos + 1..]))
187 }
188
189 fn split_2_by_slice(&self, separator: &[u8]) -> Option<(&[u8], &[u8])> {
190 find_slice_in_slice(self, separator)
191 .map(|pos| (&self[..pos], &self[pos + separator.len()..]))
192 }
193
194 fn to_hex_bytes(&self) -> Vec<u8> {
195 let mut hex = Vec::with_capacity(self.len() * 2);
196 for byte in self {
197 write!(hex, "{:02x}", byte).unwrap();
198 }
199 hex
200 }
201 }
202
203 pub trait Escaped {
204 /// Return bytes escaped for display to the user
205 fn escaped_bytes(&self) -> Vec<u8>;
206 }
207
208 impl Escaped for u8 {
209 fn escaped_bytes(&self) -> Vec<u8> {
210 let mut acc = vec![];
211 match self {
212 c @ b'\'' | c @ b'\\' => {
213 acc.push(b'\\');
214 acc.push(*c);
215 }
216 b'\t' => {
217 acc.extend(br"\\t");
218 }
219 b'\n' => {
220 acc.extend(br"\\n");
221 }
222 b'\r' => {
223 acc.extend(br"\\r");
224 }
225 c if (*c < b' ' || *c >= 127) => {
226 write!(acc, "\\x{:x}", self).unwrap();
227 }
228 c => {
229 acc.push(*c);
230 }
231 }
232 acc
233 }
234 }
235
236 impl<T: Escaped> Escaped for &[T] {
237 fn escaped_bytes(&self) -> Vec<u8> {
238 self.iter().flat_map(Escaped::escaped_bytes).collect()
239 }
240 }
241
242 impl<T: Escaped> Escaped for Vec<T> {
243 fn escaped_bytes(&self) -> Vec<u8> {
244 self.deref().escaped_bytes()
245 }
246 }
247
248 impl Escaped for &HgPath {
249 fn escaped_bytes(&self) -> Vec<u8> {
250 self.as_bytes().escaped_bytes()
251 }
252 }
253
254 #[cfg(unix)]
255 pub fn shell_quote(value: &[u8]) -> Vec<u8> {
256 if value.iter().all(|&byte| {
257 matches!(
258 byte,
259 b'a'..=b'z'
260 | b'A'..=b'Z'
261 | b'0'..=b'9'
262 | b'.'
263 | b'_'
264 | b'/'
265 | b'+'
266 | b'-'
267 )
268 }) {
269 value.to_owned()
270 } else {
271 let mut quoted = Vec::with_capacity(value.len() + 2);
272 quoted.push(b'\'');
273 for &byte in value {
274 if byte == b'\'' {
275 quoted.push(b'\\');
276 }
277 quoted.push(byte);
278 }
279 quoted.push(b'\'');
280 quoted
281 }
282 }
283
284 /// Expand `$FOO` and `${FOO}` environment variables in the given byte string
285 pub fn expand_vars(s: &[u8]) -> std::borrow::Cow<[u8]> {
286 lazy_static::lazy_static! {
287 /// https://github.com/python/cpython/blob/3.9/Lib/posixpath.py#L301
288 /// The `x` makes whitespace ignored.
289 /// `-u` disables the Unicode flag, which makes `\w` like Python with the ASCII flag.
290 static ref VAR_RE: regex::bytes::Regex =
291 regex::bytes::Regex::new(r"(?x-u)
292 \$
293 (?:
294 (\w+)
295 |
296 \{
297 ([^}]*)
298 \}
299 )
300 ").unwrap();
301 }
302 VAR_RE.replace_all(s, |captures: &regex::bytes::Captures| {
303 let var_name = crate::utils::files::get_os_str_from_bytes(
304 captures
305 .get(1)
306 .or_else(|| captures.get(2))
307 .expect("either side of `|` must participate in match")
308 .as_bytes(),
309 );
310 std::env::var_os(var_name)
311 .map(crate::utils::files::get_bytes_from_os_str)
312 .unwrap_or_else(|| {
313 // Referencing an environment variable that does not exist.
314 // Leave the $FOO reference as-is.
315 captures[0].to_owned()
316 })
317 })
318 }
319
320 /// Join items of the iterable with the given separator, similar to Python’s
321 /// `separator.join(iter)`.
322 ///
323 /// Formatting the return value consumes the iterator.
324 /// Formatting it again will produce an empty string.
325 pub fn join_display(
326 iter: impl IntoIterator<Item = impl fmt::Display>,
327 separator: impl fmt::Display,
328 ) -> impl fmt::Display {
329 JoinDisplay { iter: Cell::new(Some(iter.into_iter())), separator }
330 }
331
332 struct JoinDisplay<I, S> {
333 iter: Cell<Option<I>>,
334 separator: S,
335 }
336
337 impl<I, T, S> fmt::Display for JoinDisplay<I, S>
338 where
339 I: Iterator<Item = T>,
340 T: fmt::Display,
341 S: fmt::Display,
342 {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344 if let Some(mut iter) = self.iter.take() {
345 if let Some(first) = iter.next() {
346 first.fmt(f)?;
347 }
348 for value in iter {
349 self.separator.fmt(f)?;
350 value.fmt(f)?;
351 }
352 }
353 Ok(())
354 }
355 }
356
357 /// Returns a short representation of a user name or email address.
358 pub fn short_user(user: &[u8]) -> &[u8] {
359 let mut str = user;
360 if let Some(i) = memchr::memchr(b'@', str) {
361 str = &str[..i];
362 }
363 if let Some(i) = memchr::memchr(b'<', str) {
364 str = &str[i + 1..];
365 }
366 if let Some(i) = memchr::memchr(b' ', str) {
367 str = &str[..i];
368 }
369 if let Some(i) = memchr::memchr(b'.', str) {
370 str = &str[..i];
371 }
372 str
373 }
374
375 /// Options for [`clean_whitespace`].
376 #[derive(Copy, Clone)]
377 pub enum CleanWhitespace {
378 /// Remove whitespace at ends of lines.
379 AtEol,
380 /// Collapse consecutive whitespace characters into a single space.
381 Collapse,
382 /// Remove all whitespace characters.
383 All,
384 }
385
386 /// Normalizes whitespace in text so that it won't apppear in diffs.
387 pub fn clean_whitespace(text: &mut Vec<u8>, how: CleanWhitespace) {
388 // We copy text[i] to text[w], where w advances more slowly than i.
389 let mut w = 0;
390 match how {
391 // To match wsclean in mdiff.py, this removes "\f" (0xC).
392 CleanWhitespace::AtEol => {
393 let mut newline_dest = 0;
394 for i in 0..text.len() {
395 let char = text[i];
396 match char {
397 b' ' | b'\t' | b'\r' | 0xC => {}
398 _ => {
399 if char == b'\n' {
400 w = newline_dest;
401 }
402 newline_dest = w + 1;
403 }
404 }
405 text[w] = char;
406 w += 1;
407 }
408 }
409 // To match fixws in cext/bdiff.c, CleanWhitespace::Collapse and
410 // CleanWhitespace::All do *not* remove "\f".
411 CleanWhitespace::Collapse => {
412 for i in 0..text.len() {
413 match text[i] {
414 b' ' | b'\t' | b'\r' => {
415 if w == 0 || text[w - 1] != b' ' {
416 text[w] = b' ';
417 w += 1;
418 }
419 }
420 b'\n' if w > 0 && text[w - 1] == b' ' => {
421 text[w - 1] = b'\n';
422 }
423 char => {
424 text[w] = char;
425 w += 1;
426 }
427 }
428 }
429 }
430 CleanWhitespace::All => {
431 for i in 0..text.len() {
432 match text[i] {
433 b' ' | b'\t' | b'\r' => {}
434 char => {
435 text[w] = char;
436 w += 1;
437 }
438 }
439 }
440 }
441 }
442 text.truncate(w);
443 }
444
445 #[cfg(test)]
446 mod tests {
447 use super::*;
448
449 #[test]
450 fn test_expand_vars() {
451 // Modifying process-global state in a test isn’t great,
452 // but hopefully this won’t collide with anything.
453 unsafe { std::env::set_var("TEST_EXPAND_VAR", "1") };
454 assert_eq!(
455 expand_vars(b"before/$TEST_EXPAND_VAR/after"),
456 &b"before/1/after"[..]
457 );
458 assert_eq!(
459 expand_vars(b"before${TEST_EXPAND_VAR}${TEST_EXPAND_VAR}${TEST_EXPAND_VAR}after"),
460 &b"before111after"[..]
461 );
462 let s = b"before $SOME_LONG_NAME_THAT_WE_ASSUME_IS_NOT_AN_ACTUAL_ENV_VAR after";
463 assert_eq!(expand_vars(s), &s[..]);
464 }
465
466 #[test]
467 fn test_short_user() {
468 assert_eq!(short_user(b""), b"");
469 assert_eq!(short_user(b"Name"), b"Name");
470 assert_eq!(short_user(b"First Last"), b"First");
471 assert_eq!(short_user(b"First Last <[email protected]>"), b"user");
472 assert_eq!(short_user(b"First Last <[email protected]>"), b"user");
473 }
474
475 fn clean_ws(text: &[u8], how: CleanWhitespace) -> Vec<u8> {
476 let mut vec = text.to_vec();
477 clean_whitespace(&mut vec, how);
478 vec
479 }
480
481 #[test]
482 fn test_clean_whitespace_at_eol() {
483 // To match wsclean in mdiff.py, CleanWhitespace::AtEol only removes
484 // the final line's trailing whitespace if it ends in \n.
485 use CleanWhitespace::AtEol;
486 assert_eq!(clean_ws(b"", AtEol), b"");
487 assert_eq!(clean_ws(b" ", AtEol), b" ");
488 assert_eq!(clean_ws(b" ", AtEol), b" ");
489 assert_eq!(clean_ws(b"A", AtEol), b"A");
490 assert_eq!(clean_ws(b"\n\n\n", AtEol), b"\n\n\n");
491 assert_eq!(clean_ws(b" \n", AtEol), b"\n");
492 assert_eq!(clean_ws(b"A \n", AtEol), b"A\n");
493 assert_eq!(clean_ws(b"A B C\t\r\n", AtEol), b"A B C\n");
494 assert_eq!(clean_ws(b"A \tB C\r\nD ", AtEol), b"A \tB C\nD ");
495 assert_eq!(clean_ws(b"A\x0CB\x0C\n", AtEol), b"A\x0CB\n");
496 }
497
498 #[test]
499 fn test_clean_whitespace_collapse() {
500 use CleanWhitespace::Collapse;
501 assert_eq!(clean_ws(b"", Collapse), b"");
502 assert_eq!(clean_ws(b" ", Collapse), b" ");
503 assert_eq!(clean_ws(b" ", Collapse), b" ");
504 assert_eq!(clean_ws(b"A", Collapse), b"A");
505 assert_eq!(clean_ws(b"\n\n\n", Collapse), b"\n\n\n");
506 assert_eq!(clean_ws(b" \n", Collapse), b"\n");
507 assert_eq!(clean_ws(b"A \n", Collapse), b"A\n");
508 assert_eq!(clean_ws(b"A B C\t\r\n", Collapse), b"A B C\n");
509 assert_eq!(clean_ws(b"A \tB C\r\nD ", Collapse), b"A B C\nD ");
510 assert_eq!(clean_ws(b"A\x0CB\x0C\n", Collapse), b"A\x0CB\x0C\n");
511 }
512
513 #[test]
514 fn test_clean_whitespace_all() {
515 use CleanWhitespace::All;
516 assert_eq!(clean_ws(b"", All), b"");
517 assert_eq!(clean_ws(b" ", All), b"");
518 assert_eq!(clean_ws(b" ", All), b"");
519 assert_eq!(clean_ws(b"A", All), b"A");
520 assert_eq!(clean_ws(b"\n\n\n", All), b"\n\n\n");
521 assert_eq!(clean_ws(b" \n", All), b"\n");
522 assert_eq!(clean_ws(b"A \n", All), b"A\n");
523 assert_eq!(clean_ws(b"A B C\t\r\n", All), b"ABC\n");
524 assert_eq!(clean_ws(b"A \tB C\r\nD ", All), b"ABC\nD");
525 assert_eq!(clean_ws(b"A\x0CB\x0C\n", All), b"A\x0CB\x0C\n");
526 }
527 }