stringtheory/
clone.rs

1use crate::MetaString;
2
3/// A string type that can be cheaply cloned into a `MetaString`.
4///
5/// While callers working directly with `MetaString` already have access to determine if it is cheaply cloneable, there
6/// are a number of use cases where `MetaString` is not directly accessible. This trait allows types wrapping
7/// `MetaString` to expose the ability to cheaply clone the inner `MetaString` when possible, without having to expose
8/// it directly.
9pub trait CheapMetaString {
10    /// Attempts to cheaply clone the string.
11    ///
12    /// If the string is not cheaply cloneable, `None` is returned.
13    fn try_cheap_clone(&self) -> Option<MetaString>;
14}
15
16impl CheapMetaString for MetaString {
17    fn try_cheap_clone(&self) -> Option<MetaString> {
18        if self.is_cheaply_cloneable() {
19            Some(self.clone())
20        } else {
21            None
22        }
23    }
24}
25
26impl CheapMetaString for &str {
27    fn try_cheap_clone(&self) -> Option<MetaString> {
28        MetaString::try_inline(self)
29    }
30}
31
32impl CheapMetaString for String {
33    fn try_cheap_clone(&self) -> Option<MetaString> {
34        MetaString::try_inline(self)
35    }
36}
37
38impl<T> CheapMetaString for &T
39where
40    T: CheapMetaString,
41{
42    fn try_cheap_clone(&self) -> Option<MetaString> {
43        (*self).try_cheap_clone()
44    }
45}