Skip to content

Instantly share code, notes, and snippets.

@azriel91
Created July 29, 2023 02:12
Show Gist options
  • Save azriel91/835961367cd2852f448866cb8e222d07 to your computer and use it in GitHub Desktop.
Save azriel91/835961367cd2852f448866cb8e222d07 to your computer and use it in GitHub Desktop.
Peace framework: Random types
use std::{
fmt::Display,
ops::{Deref, DerefMut},
};
use serde::Serialize;
use type_reg::{
untagged::{BoxDataTypeDowncast, BoxDtDisplay, DataType, DataTypeWrapper, FromDataType},
TypeNameLit,
};
/// Box of a [`DataType`] that is also a [`ValueSpecRt`].
#[derive(Clone, Debug, Serialize)]
pub struct StateBoxedOpt(pub(crate) Option<BoxDtDisplay>);
impl StateBoxedOpt {
/// Returns a new `ValueSpecRtBoxed` wrapper around the provided type.
pub fn new<T>(t: T) -> Self
where
T: DataType + Display,
{
Self(Box::new(t))
}
/// Returns the inner `Box<dyn ValueSpecDataType>`.
pub fn into_inner(self) -> Option<BoxDtDisplay> {
self.0
}
}
impl Deref for StateBoxedOpt {
type Target = Option<BoxDtDisplay>;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
impl DerefMut for StateBoxedOpt {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut()
}
}
impl<T> FromDataType<T> for StateBoxedOpt
where
T: DataType + Display,
{
fn from(t: T) -> Self {
StateBoxedOpt(Box::new(t))
}
}
impl<T> BoxDataTypeDowncast<T> for StateBoxedOpt
where
T: DataType + Display,
{
fn downcast_ref(&self) -> Option<&T> {
self.0.downcast_ref::<T>()
}
fn downcast_mut(&mut self) -> Option<&mut T> {
self.0.downcast_mut::<T>()
}
}
impl DataTypeWrapper for StateBoxedOpt {
fn type_name(&self) -> TypeNameLit {
DataType::type_name(&*self.0)
}
fn clone(&self) -> Self {
Self(self.0.clone())
}
fn debug(&self) -> &dyn std::fmt::Debug {
&self.0
}
fn inner(&self) -> &dyn DataType {
&self.0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment