#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{
borrow::Cow,
cmp::Ordering,
hash::{Hash, Hasher},
sync::Arc,
};
#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CheapStr<'a>(#[cfg_attr(feature = "serde", serde(borrow))] Inner<'a>);
#[derive(Eq, Clone)]
enum Inner<'a> {
Static(&'static str),
Borrowed(&'a str),
Owned(Arc<str>),
}
impl Default for Inner<'_> {
fn default() -> Self {
Self::Static("")
}
}
impl<'a> PartialEq for Inner<'a> {
fn eq(&self, other: &Inner<'a>) -> bool {
self.as_str() == other.as_str()
}
}
impl<'a> Ord for Inner<'a> {
fn cmp(&self, other: &Inner<'a>) -> Ordering {
self.as_str().cmp(other.as_str())
}
}
impl<'a> PartialOrd for Inner<'a> {
fn partial_cmp(&self, other: &Inner<'a>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for Inner<'_> {
fn hash<H: Hasher>(&self, h: &mut H) {
self.as_str().hash(h)
}
}
impl Inner<'_> {
pub fn as_str(&self) -> &str {
match self {
Inner::Static(s) => s,
Inner::Borrowed(s) => s,
Inner::Owned(s) => s,
}
}
}
#[cfg(feature = "serde")]
impl Serialize for Inner<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de: 'a, 'a> Deserialize<'de> for Inner<'a> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
<&'a str>::deserialize(deserializer).map(Inner::Borrowed)
}
}
impl CheapStr<'_> {
pub const fn from_static(s: &'static str) -> Self {
CheapStr(Inner::Static(s))
}
pub fn as_ref(&self) -> CheapStr<'_> {
match &self.0 {
Inner::Static(s) => CheapStr(Inner::Static(s)),
Inner::Borrowed(s) => CheapStr(Inner::Borrowed(s)),
Inner::Owned(s) => CheapStr(Inner::Borrowed(s)),
}
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub fn to_owned(&self) -> CheapStr<'static> {
self.clone().into_owned()
}
pub fn into_owned(self) -> CheapStr<'static> {
match self.0 {
Inner::Static(s) => CheapStr(Inner::Static(s)),
Inner::Borrowed(s) => CheapStr(Inner::Owned(s.to_owned().into())),
Inner::Owned(s) => CheapStr(Inner::Owned(s)),
}
}
}
impl<'a> From<&'a str> for CheapStr<'a> {
fn from(value: &'a str) -> Self {
Self(Inner::Borrowed(value))
}
}
impl<'a> From<&'a String> for CheapStr<'a> {
fn from(value: &'a String) -> Self {
Self(Inner::Borrowed(value))
}
}
impl From<String> for CheapStr<'_> {
fn from(value: String) -> Self {
Self(Inner::Owned(value.into()))
}
}
impl From<Arc<str>> for CheapStr<'_> {
fn from(value: Arc<str>) -> Self {
Self(Inner::Owned(value))
}
}
impl<'a> From<Cow<'a, str>> for CheapStr<'a> {
fn from(value: Cow<'a, str>) -> Self {
match value {
Cow::Owned(value) => value.into(),
Cow::Borrowed(value) => value.into(),
}
}
}
impl<'a> From<CheapStr<'a>> for String {
fn from(value: CheapStr<'a>) -> String {
match value.0 {
Inner::Static(s) => s.into(),
Inner::Borrowed(s) => s.into(),
Inner::Owned(s) => s.to_string(),
}
}
}
impl<'a> From<&'a CheapStr<'_>> for &'a str {
fn from(value: &'a CheapStr<'_>) -> &'a str {
value.as_str()
}
}
impl std::ops::Deref for CheapStr<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl PartialEq<str> for CheapStr<'_> {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for CheapStr<'_> {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl std::fmt::Debug for CheapStr<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_str(), f)
}
}
impl std::fmt::Display for CheapStr<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.as_str(), f)
}
}
#[cfg(test)]
mod tests {
use super::CheapStr;
#[test]
fn from_string() {
let string = String::from("value");
let v = CheapStr::from(&string);
assert_eq!(v.as_str(), "value");
}
#[test]
fn test_ordering() {
let first = CheapStr::from("a".to_string());
let second = CheapStr::from_static("b");
assert!(first < second);
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use super::CheapStr;
#[test]
fn serde_round_trip() {
let s = CheapStr::from("hello");
let json = serde_json::to_string(&s).unwrap();
assert_eq!(json, "\"hello\"");
let deserialized: CheapStr<'_> = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized, s);
let owned = CheapStr::from(String::from("hello"));
assert_eq!(serde_json::to_string(&owned).unwrap(), json);
}
#[test]
fn serde_non_borrowable_input_errors() {
serde_json::from_str::<CheapStr<'_>>("\"a\\nb\"").unwrap_err();
}
#[test]
fn serde_borrowed_deserialization() {
let json = String::from("\"borrowed\"");
let s: CheapStr<'_> = serde_json::from_str(&json).unwrap();
assert_eq!(s.as_str(), "borrowed");
assert!(std::ptr::eq(s.as_str().as_ptr(), json[1..].as_ptr()));
}
}