Skip to main content

kova_native_core/
shared_string.rs

1//! Cheaply clonable immutable strings.
2
3use std::borrow::Borrow;
4use std::fmt;
5use std::ops::Deref;
6use std::rc::Rc;
7
8/// An immutable string that is either `'static` or reference counted.
9///
10/// Cloning never allocates, which matters because text content flows through
11/// element builders, bindings and caches.
12#[derive(Clone)]
13pub enum SharedString {
14    Static(&'static str),
15    Owned(Rc<str>),
16}
17
18impl SharedString {
19    pub const fn new_static(s: &'static str) -> Self {
20        SharedString::Static(s)
21    }
22
23    pub fn as_str(&self) -> &str {
24        match self {
25            SharedString::Static(s) => s,
26            SharedString::Owned(s) => s,
27        }
28    }
29}
30
31impl Default for SharedString {
32    fn default() -> Self {
33        SharedString::Static("")
34    }
35}
36
37impl Deref for SharedString {
38    type Target = str;
39    fn deref(&self) -> &str {
40        self.as_str()
41    }
42}
43
44impl AsRef<str> for SharedString {
45    fn as_ref(&self) -> &str {
46        self.as_str()
47    }
48}
49
50impl Borrow<str> for SharedString {
51    fn borrow(&self) -> &str {
52        self.as_str()
53    }
54}
55
56impl PartialEq for SharedString {
57    fn eq(&self, other: &Self) -> bool {
58        self.as_str() == other.as_str()
59    }
60}
61
62impl Eq for SharedString {}
63
64impl PartialEq<str> for SharedString {
65    fn eq(&self, other: &str) -> bool {
66        self.as_str() == other
67    }
68}
69
70impl PartialEq<&str> for SharedString {
71    fn eq(&self, other: &&str) -> bool {
72        self.as_str() == *other
73    }
74}
75
76impl std::hash::Hash for SharedString {
77    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
78        self.as_str().hash(state)
79    }
80}
81
82impl fmt::Debug for SharedString {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        fmt::Debug::fmt(self.as_str(), f)
85    }
86}
87
88impl fmt::Display for SharedString {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        fmt::Display::fmt(self.as_str(), f)
91    }
92}
93
94impl From<&'static str> for SharedString {
95    fn from(s: &'static str) -> Self {
96        SharedString::Static(s)
97    }
98}
99
100impl From<String> for SharedString {
101    fn from(s: String) -> Self {
102        SharedString::Owned(s.into())
103    }
104}
105
106impl From<&String> for SharedString {
107    fn from(s: &String) -> Self {
108        SharedString::Owned(s.as_str().into())
109    }
110}
111
112impl From<Rc<str>> for SharedString {
113    fn from(s: Rc<str>) -> Self {
114        SharedString::Owned(s)
115    }
116}
117
118impl From<char> for SharedString {
119    fn from(c: char) -> Self {
120        SharedString::Owned(c.to_string().into())
121    }
122}