shared_string.rs

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