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
/// Replaces multiple `str` at once, avoiding intermediate allocations. It returns a new `String` containing the result. Values passed by value keep ownership.
/// 
/// # Examples
/// 
/// ```
/// 
/// let s = "Ciao bello";
/// 
/// let s_removed = remove_matches!( s; "ia", "b" );
/// 
/// assert_eq!(s_removed, "Co ello");
#[macro_export]
macro_rules! remove_matches {
    ( $string:expr; $( $pat:expr ),* ) => ({
        let mut new_string: String = String::new();
        let mut to_skip = 0;
        let mut next_start = 0;
        
        'outer: for i in 0..$string.len() {
            if to_skip > 0 {
                to_skip -= 1;
                continue 'outer
            }
            $(
                unsafe {
                    // It's the element that must be replaced.
                    
                    let pat_len = $pat.len();
                    // Avoids out of bounds bugs.
                    if i + pat_len > $string.len() { break 'outer }
                    // This is safe thanks to the check above.
                    if *$pat == *$string.get_unchecked(i..i + pat_len) {
                        new_string.push_str( $string.get_unchecked(next_start..i));
                        next_start = i + pat_len;
                        to_skip += pat_len - 1;
                    }
                }
            )*
            
        }
        
        unsafe {
            new_string.push_str($string.get_unchecked(next_start..));
        }
        new_string
    });
}