#[cfg(feature = "alloc")]
mod alloc;
mod core;
use rancor::{Fallible, Strategy};
#[cfg(feature = "alloc")]
pub use self::alloc::*;
pub use self::core::*;
use crate::SerializeUnsized;
pub trait Sharing<E = <Self as Fallible>::Error> {
fn get_shared_ptr(&self, address: usize) -> Option<usize>;
fn add_shared_ptr(&mut self, address: usize, pos: usize) -> Result<(), E>;
}
impl<T, E> Sharing<E> for Strategy<T, E>
where
T: Sharing<E> + ?Sized,
{
fn get_shared_ptr(&self, address: usize) -> Option<usize> {
T::get_shared_ptr(self, address)
}
fn add_shared_ptr(&mut self, address: usize, pos: usize) -> Result<(), E> {
T::add_shared_ptr(self, address, pos)
}
}
pub trait SharingExt<E>: Sharing<E> {
#[inline]
fn get_shared<T: ?Sized>(&self, value: &T) -> Option<usize> {
self.get_shared_ptr(value as *const T as *const () as usize)
}
#[inline]
fn add_shared<T: ?Sized>(
&mut self,
value: &T,
pos: usize,
) -> Result<(), E> {
self.add_shared_ptr(value as *const T as *const () as usize, pos)
}
#[inline]
fn serialize_shared<T: SerializeUnsized<Self> + ?Sized>(
&mut self,
value: &T,
) -> Result<usize, <Self as Fallible>::Error>
where
Self: Fallible<Error = E>,
{
if let Some(pos) = self.get_shared(value) {
Ok(pos)
} else {
let pos = value.serialize_unsized(self)?;
self.add_shared(value, pos)?;
Ok(pos)
}
}
}
impl<S, E> SharingExt<E> for S where S: Sharing<E> + ?Sized {}