1use alloc::borrow::Cow;
2
3use crate::{to_substring_in_place, Pattern};
4
5pub trait Replace<'a> {
7 fn replace_cow<P: Pattern>(self, from: P, to: &str) -> Cow<'a, str>;
11
12 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}