use serde::{Deserialize, Serialize};
use std::{fmt, ops, sync::Arc};
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct SharedCow<T: Clone>(Arc<T>);
impl<T: Clone> SharedCow<T> {
pub fn new(value: T) -> SharedCow<T> {
SharedCow(Arc::new(value))
}
pub fn into_owned(self: SharedCow<T>) -> T {
match Arc::try_unwrap(self.0) {
Ok(value) => value,
Err(arc) => (*arc).clone(),
}
}
pub fn to_mut(&mut self) -> &mut T {
Arc::make_mut(&mut self.0)
}
pub fn into_arc(value: SharedCow<T>) -> Arc<T> {
value.0
}
pub fn ref_count(value: &SharedCow<T>) -> usize {
Arc::strong_count(&value.0)
}
}
impl<T> From<T> for SharedCow<T>
where
T: Clone,
{
fn from(value: T) -> Self {
SharedCow::new(value)
}
}
impl<T> From<Arc<T>> for SharedCow<T>
where
T: Clone,
{
fn from(value: Arc<T>) -> Self {
SharedCow(value)
}
}
impl<T> fmt::Debug for SharedCow<T>
where
T: fmt::Debug + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(*self.0).fmt(f)
}
}
impl<T> fmt::Display for SharedCow<T>
where
T: fmt::Display + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(*self.0).fmt(f)
}
}
impl<T: Clone> Serialize for SharedCow<T>
where
T: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de, T: Clone> Deserialize<'de> for SharedCow<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(Arc::new).map(SharedCow)
}
}
impl<T: Clone> ops::Deref for SharedCow<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}