tpnote_lib/clone_ext.rs
1//! Extension trait adding a `shallow_clone()` method to `Cow`.
2use std::borrow::Cow;
3
4pub trait CloneExt<'b> {
5 /// Clone a `Cow` without memory allocation.
6 /// Note, the original must outlive the clone! Use case:
7 /// ```no_run
8 /// use crate::tpnote_lib::clone_ext::CloneExt;
9 /// use std::borrow::Cow;
10 /// fn do_something_or_nothing(v: Cow<str>) -> Cow<str> {
11 /// if v.len() > 3 {
12 /// let s = "Hello ".to_string() + &*v;
13 /// Cow::Owned(s)
14 /// } else {
15 /// v
16 /// }
17 /// }
18 ///
19 /// // Sometimes, we only have a `&Cow`, but we need a `Cow`!
20 /// let a: &Cow<str> = &Cow::Owned("world!".to_string());
21 /// let b: Cow<str> = a.shallow_clone();
22 /// assert_eq!(do_something_or_nothing(b), "Hello world!");
23 ///
24 /// let a: &Cow<str> = &Cow::Owned("ld!".to_string());
25 /// let b: Cow<str> = a.shallow_clone();
26 /// assert_eq!(do_something_or_nothing(b), "ld!");
27 /// ```
28 fn shallow_clone(&'b self) -> Cow<'b, str>;
29}
30
31impl<'b> CloneExt<'b> for Cow<'b, str> {
32 fn shallow_clone(&'b self) -> Cow<'b, str> {
33 // match *self {
34 // Self::Borrowed(b) => Self::Borrowed(b),
35 // Self::Owned(ref o) => Self::Borrowed(o.as_ref()),
36 // }
37 // // This is equivalent to:
38 Cow::Borrowed(&**self)
39 }
40}