Skip to main content

str_utils/
replace.rs

1use alloc::borrow::Cow;
2
3use crate::{to_substring_in_place, Pattern};
4
5/// To extend `str` and `Cow<str>` to have `replace_cow` and `replacen_cow` methods.
6pub trait Replace<'a> {
7    /// Replaces all matches of a pattern with another string, returning a `Cow<str>` to avoid allocation when possible.
8    ///
9    /// When the input is borrowed and removing matches only changes the prefix or suffix, the returned value also borrows the remaining substring.
10    fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str>;
11
12    /// Replaces at most `count` matches of a pattern with another string, returning a `Cow<str>` to avoid allocation when possible.
13    ///
14    /// When the input is borrowed and removing matches only changes the prefix or suffix, the returned value also borrows the remaining substring.
15    fn replacen_cow<P: Pattern>(self, from: P, to: &str, count: usize) -> Cow<'a, str>;
16}
17
18impl<'a> Replace<'a> for &'a str {
19    #[inline]
20    fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str> {
21        from.replace_from(self, to)
22    }
23
24    #[inline]
25    fn replacen_cow<P: Pattern>(self, from: P, to: &str, count: usize) -> Cow<'a, str> {
26        from.replacen_from(self, to, count)
27    }
28}
29
30impl<'a> Replace<'a> for Cow<'a, str> {
31    #[inline]
32    fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str> {
33        match self {
34            Cow::Borrowed(s) => s.replace_cow(from, to),
35            Cow::Owned(s) => match s.as_str().replace_cow(from, to) {
36                Cow::Borrowed(ss) => Cow::Owned(unsafe { to_substring_in_place!(s, ss) }),
37                Cow::Owned(s) => Cow::Owned(s),
38            },
39        }
40    }
41
42    #[inline]
43    fn replacen_cow<P: Pattern>(self, from: P, to: &str, count: usize) -> Cow<'a, str> {
44        match self {
45            Cow::Borrowed(s) => s.replacen_cow(from, to, count),
46            Cow::Owned(s) => match s.as_str().replacen_cow(from, to, count) {
47                Cow::Borrowed(ss) => Cow::Owned(unsafe { to_substring_in_place!(s, ss) }),
48                Cow::Owned(s) => Cow::Owned(s),
49            },
50        }
51    }
52}