1use derive_more::{Deref, DerefMut};
2use serde::{Deserialize, Serialize};
3use std::{borrow::Borrow, sync::Arc};
4use util::arc_cow::ArcCow;
5
6/// A shared string is an immutable string that can be cheaply cloned in GPUI
7/// tasks. Essentially an abstraction over an `Arc<str>` and `&'static str`,
8#[derive(Deref, DerefMut, Eq, PartialEq, PartialOrd, Ord, Hash, Clone)]
9pub struct SharedString(ArcCow<'static, str>);
10
11impl Default for SharedString {
12 fn default() -> Self {
13 Self(ArcCow::Owned("".into()))
14 }
15}
16
17impl AsRef<str> for SharedString {
18 fn as_ref(&self) -> &str {
19 &self.0
20 }
21}
22
23impl Borrow<str> for SharedString {
24 fn borrow(&self) -> &str {
25 self.as_ref()
26 }
27}
28
29impl std::fmt::Debug for SharedString {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 self.0.fmt(f)
32 }
33}
34
35impl std::fmt::Display for SharedString {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 write!(f, "{}", self.0.as_ref())
38 }
39}
40
41impl PartialEq<String> for SharedString {
42 fn eq(&self, other: &String) -> bool {
43 self.as_ref() == other
44 }
45}
46
47impl PartialEq<SharedString> for String {
48 fn eq(&self, other: &SharedString) -> bool {
49 self == other.as_ref()
50 }
51}
52
53impl PartialEq<str> for SharedString {
54 fn eq(&self, other: &str) -> bool {
55 self.as_ref() == other
56 }
57}
58
59impl<'a> PartialEq<&'a str> for SharedString {
60 fn eq(&self, other: &&'a str) -> bool {
61 self.as_ref() == *other
62 }
63}
64
65impl From<SharedString> for Arc<str> {
66 fn from(val: SharedString) -> Self {
67 match val.0 {
68 ArcCow::Borrowed(borrowed) => Arc::from(borrowed),
69 ArcCow::Owned(owned) => owned.clone(),
70 }
71 }
72}
73
74impl<T: Into<ArcCow<'static, str>>> From<T> for SharedString {
75 fn from(value: T) -> Self {
76 Self(value.into())
77 }
78}
79
80impl From<SharedString> for String {
81 fn from(val: SharedString) -> Self {
82 val.0.to_string()
83 }
84}
85
86impl Serialize for SharedString {
87 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
88 where
89 S: serde::Serializer,
90 {
91 serializer.serialize_str(self.as_ref())
92 }
93}
94
95impl<'de> Deserialize<'de> for SharedString {
96 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
97 where
98 D: serde::Deserializer<'de>,
99 {
100 let s = String::deserialize(deserializer)?;
101 Ok(SharedString::from(s))
102 }
103}