rust_assembler/str/remove_matches.rs
1
2/// Replaces multiple `str` at once, avoiding intermediate allocations. It returns a new `String` containing the result. Values passed by value keep ownership.
3///
4/// # Examples
5///
6/// ```
7///
8/// let s = "Ciao bello";
9///
10/// let s_removed = remove_matches!( s; "ia", "b" );
11///
12/// assert_eq!(s_removed, "Co ello");
13#[macro_export]
14macro_rules! remove_matches {
15 ( $string:expr; $( $pat:expr ),* ) => ({
16 let mut new_string: String = String::new();
17
18 let mut to_skip = 0;
19 let mut next_start = 0;
20
21 'outer: for i in 0..$string.len() {
22 if to_skip > 0 {
23 to_skip -= 1;
24 continue 'outer
25 }
26
27 $(
28 unsafe {
29 // It's the element that must be replaced.
30
31 let pat_len = $pat.len();
32 // Avoids out of bounds bugs.
33 if i + pat_len > $string.len() { break 'outer }
34
35 // This is safe thanks to the check above.
36 if *$pat == *$string.get_unchecked(i..i + pat_len) {
37 new_string.push_str( $string.get_unchecked(next_start..i));
38 next_start = i + pat_len;
39 to_skip += pat_len - 1;
40 }
41 }
42 )*
43
44 }
45
46 unsafe {
47 new_string.push_str($string.get_unchecked(next_start..));
48 }
49
50 new_string
51 });
52}