shared_string.rs

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