use std::any::{Any, TypeId};
use std::fmt;
use std::rc::Rc;
use super::{Archive, ArchiveError, Decoder, Encoder};
#[derive(Clone)]
pub struct External(Rc<dyn Any>);
impl External {
pub fn new(value: impl Any) -> Self {
Self(Rc::new(value))
}
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
self.0.downcast_ref()
}
pub(super) fn same(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl fmt::Debug for External {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("External(..)")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KindOf {
pub id: TypeId,
pub name: &'static str,
}
impl KindOf {
pub fn of<T: ?Sized + 'static>(name: &'static str) -> Self {
Self {
id: TypeId::of::<T>(),
name,
}
}
}
pub trait ProgramKinds {
fn encode_kind(
&self,
of: KindOf,
_value: &dyn Any,
_encoder: &mut Encoder<'_>,
) -> Result<(), ArchiveError> {
Err(ArchiveError::unsupported(format!(
"a {} of a type of the program's",
of.name
)))
}
fn decode_kind(
&self,
of: KindOf,
_decoder: &mut Decoder<'_>,
) -> Result<Box<dyn Any>, ArchiveError> {
Err(ArchiveError::invalid(format!(
"a {} of a type of a program's, which this program cannot read",
of.name
)))
}
fn function(
&self,
_function: TypeId,
_origin: &External,
) -> Result<Box<dyn Any>, ArchiveError> {
Err(ArchiveError::invalid(
"a function of a program's, which this program cannot rebuild",
))
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct NoProgram;
impl ProgramKinds for NoProgram {}
pub struct ProgramFn<F: ?Sized> {
function: Rc<F>,
origin: Option<External>,
}
impl<F: ?Sized> ProgramFn<F> {
pub fn new(function: Rc<F>) -> Self {
Self {
function,
origin: None,
}
}
pub fn with_origin(function: Rc<F>, origin: External) -> Self {
Self {
function,
origin: Some(origin),
}
}
pub fn get(&self) -> &F {
&self.function
}
pub fn shared(&self) -> &Rc<F> {
&self.function
}
pub fn origin(&self) -> Option<&External> {
self.origin.as_ref()
}
}
impl<F: ?Sized> Clone for ProgramFn<F> {
fn clone(&self) -> Self {
Self {
function: Rc::clone(&self.function),
origin: self.origin.clone(),
}
}
}
impl<F: ?Sized> fmt::Debug for ProgramFn<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProgramFn")
.field("archivable", &self.origin.is_some())
.finish_non_exhaustive()
}
}
impl<F: ?Sized + 'static> Archive for ProgramFn<F> {
fn encode(&self, encoder: &mut Encoder<'_>) -> Result<(), ArchiveError> {
let origin = self
.origin
.as_ref()
.ok_or_else(|| ArchiveError::unsupported("a function given without an origin"))?;
encoder.write_external(origin);
Ok(())
}
fn decode(decoder: &mut Decoder<'_>) -> Result<Self, ArchiveError> {
let origin = decoder.read_external()?;
let function = decoder.program_function::<Rc<F>>(&origin)?;
Ok(Self::with_origin(function, origin))
}
}