use std::any::Any;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, RwLock};
use super::{Sys, ValueHandle};
use crate::{InStream, ObjectRef, OutStream};
pub struct AbstractValue<T: ?Sized> {
handle: ValueHandle,
ops: Arc<T>,
}
impl<T: ?Sized> AbstractValue<T> {
pub fn new(handle: ValueHandle, ops: Arc<T>) -> AbstractValue<T> {
AbstractValue { handle, ops }
}
pub fn handle(&self) -> &ValueHandle {
&self.handle
}
pub fn ops(&self) -> &Arc<T> {
&self.ops
}
pub fn ptr_eq(&self, other: &AbstractValue<T>) -> bool {
self.handle.ptr_eq(&other.handle)
}
}
impl<T: ?Sized> Clone for AbstractValue<T> {
fn clone(&self) -> Self {
AbstractValue {
handle: self.handle.clone(),
ops: self.ops.clone(),
}
}
}
impl<T: ?Sized> fmt::Debug for AbstractValue<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.handle.fmt(f)
}
}
pub struct Upcast<T: ?Sized>(pub Arc<T>);
impl<T: ?Sized> fmt::Debug for Upcast<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Upcast")
}
}
pub type SupportedFn = fn(&ValueHandle) -> Option<Box<dyn Any + Send>>;
type Supported = BTreeMap<(&'static str, &'static str), SupportedFn>;
static SUPPORTED: RwLock<Supported> = RwLock::new(BTreeMap::new());
pub fn register_supported(abstract_id: &'static str, value_id: &'static str, f: SupportedFn) {
SUPPORTED
.write()
.unwrap_or_else(|e| e.into_inner())
.insert((abstract_id, value_id), f);
}
pub fn supported<A: 'static>(abstract_id: &str, v: &ValueHandle) -> Option<A> {
let table = SUPPORTED.read().unwrap_or_else(|e| e.into_inner());
v.info().ancestors.iter().find_map(|id| {
let f = table.get(&(abstract_id, *id))?;
f(v)?.downcast::<A>().ok().map(|a| *a)
})
}
pub fn write_abstract_object(obj: Option<&ObjectRef>, out: &mut OutStream<'_>) -> Sys<()> {
out.write_bool(true);
out.write_object(obj)
}
pub fn write_abstract_value(v: &ValueHandle, out: &mut OutStream<'_>) -> Sys<()> {
out.write_bool(false);
ValueHandle::write(Some(v), out)
}
pub fn read_abstract<A: 'static>(
input: &mut InStream<'_>,
abstract_id: &str,
object: fn(ObjectRef) -> A,
) -> Sys<Option<A>> {
if input.read_bool().map_err(|_| input.marshal_error())? {
return Ok(input.read_object()?.map(object));
}
read_abstract_value(input, abstract_id)
}
pub fn read_abstract_value<A: 'static>(
input: &mut InStream<'_>,
abstract_id: &str,
) -> Sys<Option<A>> {
match ValueHandle::read_base(input)? {
None => Ok(None),
Some(v) => supported(abstract_id, &v)
.map(Some)
.ok_or_else(|| input.marshal_error()),
}
}