1#[cfg(feature = "serde")]
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3
4use alloc::{borrow::Cow, string::String, sync::Arc};
5use core::{
6 cmp::Ordering,
7 hash::{Hash, Hasher},
8 ptr::NonNull,
9};
10
11#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub struct CheapStr<'a>(#[cfg_attr(feature = "serde", serde(borrow))] Inner<'a>);
32
33#[derive(Clone)]
34enum Inner<'a> {
35 Static(&'static str),
36 Borrowed(&'a str),
37 Owned(ArcStr),
38}
39
40impl Default for Inner<'_> {
41 fn default() -> Self {
42 Self::Static("")
43 }
44}
45
46impl<'a> PartialEq for Inner<'a> {
47 fn eq(&self, other: &Inner<'a>) -> bool {
48 self.as_str() == other.as_str()
49 }
50}
51
52impl Eq for Inner<'_> {}
53
54impl<'a> Ord for Inner<'a> {
55 fn cmp(&self, other: &Inner<'a>) -> Ordering {
56 self.as_str().cmp(other.as_str())
57 }
58}
59
60impl<'a> PartialOrd for Inner<'a> {
61 fn partial_cmp(&self, other: &Inner<'a>) -> Option<Ordering> {
62 Some(self.cmp(other))
63 }
64}
65
66impl Hash for Inner<'_> {
67 fn hash<H: Hasher>(&self, h: &mut H) {
68 self.as_str().hash(h)
69 }
70}
71
72impl Inner<'_> {
73 pub const fn as_str(&self) -> &str {
75 match self {
76 Inner::Static(s) => s,
77 Inner::Borrowed(s) => s,
78 Inner::Owned(s) => s.as_str(),
79 }
80 }
81}
82
83#[cfg(feature = "serde")]
84impl Serialize for Inner<'_> {
85 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
86 s.serialize_str(self.as_str())
87 }
88}
89
90#[cfg(feature = "serde")]
91impl<'de: 'a, 'a> Deserialize<'de> for Inner<'a> {
92 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
93 where
94 D: Deserializer<'de>,
95 {
96 <&'a str>::deserialize(deserializer).map(Inner::Borrowed)
97 }
98}
99
100impl CheapStr<'_> {
101 pub const fn from_static(s: &'static str) -> Self {
103 CheapStr(Inner::Static(s))
104 }
105
106 pub fn as_ref(&self) -> CheapStr<'_> {
108 match &self.0 {
109 Inner::Static(s) => CheapStr(Inner::Static(s)),
110 Inner::Borrowed(s) => CheapStr(Inner::Borrowed(s)),
111 Inner::Owned(s) => CheapStr(Inner::Borrowed(s.as_str())),
112 }
113 }
114
115 pub const fn as_str(&self) -> &str {
129 self.0.as_str()
130 }
131
132 pub fn to_owned(&self) -> CheapStr<'static> {
134 self.clone().into_owned()
135 }
136
137 pub fn into_owned(self) -> CheapStr<'static> {
139 match self.0 {
140 Inner::Static(s) => CheapStr(Inner::Static(s)),
141 Inner::Borrowed(s) => CheapStr::from(Arc::<str>::from(s)),
142 Inner::Owned(s) => CheapStr(Inner::Owned(s)),
143 }
144 }
145}
146
147impl<'a> From<&'a str> for CheapStr<'a> {
148 fn from(value: &'a str) -> Self {
149 Self(Inner::Borrowed(value))
150 }
151}
152
153impl<'a> From<&'a String> for CheapStr<'a> {
154 fn from(value: &'a String) -> Self {
155 Self(Inner::Borrowed(value))
156 }
157}
158
159impl From<String> for CheapStr<'_> {
160 fn from(value: String) -> Self {
161 Self::from(Arc::<str>::from(value))
162 }
163}
164
165impl From<Arc<str>> for CheapStr<'_> {
166 fn from(value: Arc<str>) -> Self {
167 Self(Inner::Owned(ArcStr::from(value)))
168 }
169}
170
171impl<'a> From<Cow<'a, str>> for CheapStr<'a> {
172 fn from(value: Cow<'a, str>) -> Self {
173 match value {
174 Cow::Owned(value) => value.into(),
175 Cow::Borrowed(value) => value.into(),
176 }
177 }
178}
179
180impl<'a> From<CheapStr<'a>> for String {
181 fn from(value: CheapStr<'a>) -> String {
182 match value.0 {
183 Inner::Static(s) => s.into(),
184 Inner::Borrowed(s) => s.into(),
185 Inner::Owned(s) => s.as_str().into(),
186 }
187 }
188}
189
190impl<'a> From<&'a CheapStr<'_>> for &'a str {
191 fn from(value: &'a CheapStr<'_>) -> &'a str {
192 value.as_str()
193 }
194}
195
196impl core::ops::Deref for CheapStr<'_> {
197 type Target = str;
198
199 fn deref(&self) -> &Self::Target {
200 self.as_str()
201 }
202}
203
204impl PartialEq<str> for CheapStr<'_> {
205 fn eq(&self, other: &str) -> bool {
206 self.as_str() == other
207 }
208}
209
210impl PartialEq<&str> for CheapStr<'_> {
211 fn eq(&self, other: &&str) -> bool {
212 self.as_str() == *other
213 }
214}
215
216impl core::fmt::Debug for CheapStr<'_> {
217 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
218 core::fmt::Debug::fmt(self.as_str(), f)
219 }
220}
221
222impl core::fmt::Display for CheapStr<'_> {
223 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
224 core::fmt::Display::fmt(self.as_str(), f)
225 }
226}
227
228struct ArcStr(NonNull<str>);
241
242impl ArcStr {
243 const fn as_str(&self) -> &str {
244 unsafe { self.0.as_ref() }
251 }
252}
253
254impl From<Arc<str>> for ArcStr {
255 fn from(value: Arc<str>) -> Self {
256 let ptr = Arc::into_raw(value).cast_mut();
258 Self(unsafe { NonNull::new_unchecked(ptr) })
261 }
262}
263
264impl Clone for ArcStr {
265 fn clone(&self) -> Self {
266 unsafe { Arc::increment_strong_count(self.0.as_ptr()) };
271
272 Self(self.0)
273 }
274}
275
276impl Drop for ArcStr {
277 fn drop(&mut self) {
278 drop(unsafe { Arc::from_raw(self.0.as_ptr()) });
283 }
284}
285
286unsafe impl Send for ArcStr {}
291
292unsafe impl Sync for ArcStr {}
296
297#[cfg(test)]
298mod tests {
299 use super::CheapStr;
300 use alloc::{
301 string::{String, ToString},
302 sync::Arc,
303 };
304 use core::panic::{RefUnwindSafe, UnwindSafe};
305
306 #[test]
307 fn from_string() {
308 let string = String::from("value");
309 let v = CheapStr::from(&string);
310 assert_eq!(v.as_str(), "value");
311 }
312
313 #[test]
314 fn test_ordering() {
315 let first = CheapStr::from("a".to_string());
316 let second = CheapStr::from_static("b");
317 assert!(first < second);
318 }
319
320 #[test]
321 fn as_str_in_const() {
322 const STATIC: &CheapStr<'static> = &CheapStr::from_static("static");
323 const STATIC_STR: &str = STATIC.as_str();
324 assert_eq!(STATIC_STR, "static");
325 }
326
327 #[test]
328 fn shared_data() {
329 let arc = Arc::<str>::from("shared");
330 let s = CheapStr::from(arc.clone());
331 assert_eq!(s.as_str(), "shared");
332 assert_eq!(Arc::strong_count(&arc), 2);
333
334 let clone = s.clone();
336 assert_eq!(Arc::strong_count(&arc), 3);
337 assert!(core::ptr::eq(clone.as_str(), &*arc));
338 let owned = s.into_owned();
339 assert_eq!(Arc::strong_count(&arc), 3);
340 assert!(core::ptr::eq(owned.as_str(), &*arc));
341
342 drop(clone);
343 assert_eq!(String::from(owned), "shared");
344 assert_eq!(Arc::strong_count(&arc), 1);
345 }
346
347 #[test]
348 fn auto_traits() {
349 fn assert_auto_traits<T>()
350 where
351 T: Send + Sync + Unpin + UnwindSafe + RefUnwindSafe,
352 {
353 }
354
355 assert_auto_traits::<CheapStr<'_>>();
356 }
357}
358
359#[cfg(all(test, feature = "serde"))]
360mod serde_tests {
361 use super::CheapStr;
362 use alloc::string::String;
363
364 #[test]
365 fn serde_round_trip() {
366 let s = CheapStr::from("hello");
367 let json = serde_json::to_string(&s).unwrap();
368 assert_eq!(json, "\"hello\"");
369 let deserialized: CheapStr<'_> = serde_json::from_str(&json).unwrap();
370 assert_eq!(deserialized, s);
371
372 let owned = CheapStr::from(String::from("hello"));
374 assert_eq!(serde_json::to_string(&owned).unwrap(), json);
375 }
376
377 #[test]
378 fn serde_non_borrowable_input_errors() {
379 serde_json::from_str::<CheapStr<'_>>("\"a\\nb\"").unwrap_err();
382 }
383
384 #[test]
385 fn serde_borrowed_deserialization() {
386 let json = String::from("\"borrowed\"");
387 let s: CheapStr<'_> = serde_json::from_str(&json).unwrap();
388 assert_eq!(s.as_str(), "borrowed");
389 assert!(core::ptr::eq(s.as_str().as_ptr(), json[1..].as_ptr()));
391 }
392}