Skip to main content

str_utils/
replace.rs

1use alloc::borrow::Cow;
2
3use crate::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    fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str>;
9
10    /// Replaces at most `count` matches of a pattern with another string, returning a `Cow<str>` to avoid allocation when possible.
11    fn replacen_cow<P: Pattern>(self, from: P, to: &str, count: usize) -> Cow<'a, str>;
12}
13
14impl<'a> Replace<'a> for &'a str {
15    #[inline]
16    fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str> {
17        from.replace_from(self, to)
18    }
19
20    #[inline]
21    fn replacen_cow<P: Pattern>(self, from: P, to: &str, count: usize) -> Cow<'a, str> {
22        from.replacen_from(self, to, count)
23    }
24}
25
26impl<'a> Replace<'a> for Cow<'a, str> {
27    #[inline]
28    fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str> {
29        match self {
30            Cow::Borrowed(s) => s.replace_cow(from, to),
31            Cow::Owned(s) => Cow::Owned(cow_into_owned!(s, s.as_str().replace_cow(from, to),)),
32        }
33    }
34
35    #[inline]
36    fn replacen_cow<P: Pattern>(self, from: P, to: &str, count: usize) -> Cow<'a, str> {
37        match self {
38            Cow::Borrowed(s) => s.replacen_cow(from, to, count),
39            Cow::Owned(s) => {
40                Cow::Owned(cow_into_owned!(s, s.as_str().replacen_cow(from, to, count),))
41            },
42        }
43    }
44}