use crate::*;
use std::{
fmt::{Debug, Display},
sync::Arc,
};
pub enum Str {
Static(&'static str),
Rc(Arc<String>),
Owned(String),
}
impl Display for Str {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Str::Static(s) => write!(f, "{}", s),
Str::Rc(s) => write!(f, "{}", s),
Str::Owned(s) => write!(f, "{}", s),
}
}
}
impl Clone for Str {
fn clone(&self) -> Self {
match self {
Str::Static(s) => Str::Static(s),
Str::Rc(s) => Str::Rc(Arc::clone(s)),
Str::Owned(s) => Str::Owned(s.clone()),
}
}
}
impl Debug for Str {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Str::Static(s) => write!(f, "Str::Static({:?})", s),
Str::Rc(s) => write!(f, "Str::Rc({:?})", s),
Str::Owned(s) => write!(f, "Str::Owned({:?})", s),
}
}
}
impl Str {
pub fn as_str(&self) -> &str {
match self {
Str::Static(s) => s,
Str::Rc(s) => s.as_str(),
Str::Owned(s) => s.as_str(),
}
}
pub fn from_static(s: &'static str) -> Self {
Str::Static(s)
}
pub fn from_owned(s: String) -> Self {
Str::Owned(s)
}
pub fn from_rc(s: Arc<String>) -> Self {
Str::Rc(s)
}
pub fn take(self) -> String {
match self {
Str::Static(s) => s.to_string(),
Str::Rc(s) => s.as_ref().clone(),
Str::Owned(s) => s,
}
}
pub fn into_string(self) -> String {
self.take()
}
pub fn is_static(&self) -> bool {
matches!(self, Str::Static(_))
}
pub fn is_owned(&self) -> bool {
matches!(self, Str::Owned(_))
}
pub fn is_rc(&self) -> bool {
matches!(self, Str::Rc(_))
}
}
impl From<Str> for Value {
fn from(s: Str) -> Self {
Value::String(s)
}
}
impl From<String> for Value {
fn from(s: String) -> Self {
Value::String(Str::Owned(s))
}
}
impl From<&'static str> for Value {
fn from(s: &'static str) -> Self {
Value::String(Str::Static(s))
}
}
impl From<Arc<String>> for Value {
fn from(s: Arc<String>) -> Self {
Value::String(Str::Rc(s))
}
}
impl From<&'static str> for Str {
fn from(s: &'static str) -> Self {
Str::Static(s)
}
}
impl From<String> for Str {
fn from(s: String) -> Self {
Str::Owned(s)
}
}
impl From<Arc<String>> for Str {
fn from(s: Arc<String>) -> Self {
Str::Rc(s)
}
}
impl From<Str> for String {
fn from(s: Str) -> Self {
s.take()
}
}