use super::{Archivable, Root};
use crate::archive::Portable;
use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::evolution::{Evolution, SubEvolution};
use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use crate::containers::matrix::{Matrix, SubMatrix};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::model::{Model, SubModel};
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::any::Any;
fn unknown(tag: &str) -> PyrucastError {
PyrucastError::Message(format!(
"archive: unknown object type \"{tag}\" — the file was written by a \
build that knows a type this one does not"
))
}
fn mismatch(tag: &str) -> PyrucastError {
PyrucastError::Message(format!(
"archive: a record tagged \"{tag}\" does not hold a {tag} — the file is damaged"
))
}
macro_rules! shared {
($($ty:ty => $variant:ident),* $(,)?) => {
pub(crate) fn decode_node(tag: &str, bytes: &[u8]) -> Result<Box<dyn Any + Send + Sync>> {
$(
if tag == <$ty as Archivable>::TAG {
let mut value = <$ty as Portable>::from_bytes(bytes)?;
value.on_load();
return Ok(Box::new(Handle::new(value)));
}
)*
Err(unknown(tag))
}
pub(crate) fn wrap_root(tag: &str, any: &(dyn Any + Send + Sync)) -> Result<Root> {
$(
if tag == <$ty as Archivable>::TAG {
return any
.downcast_ref::<Handle<$ty>>()
.cloned()
.map(Root::$variant)
.ok_or_else(|| mismatch(tag));
}
)*
Err(unknown(tag))
}
};
}
shared! {
Coords => Coords,
SubMesh => SubMesh,
SubFiniteElementSpace => SubFiniteElementSpace,
SubNodeField => SubNodeField,
SubElementField => SubElementField,
SubEvolution => SubEvolution,
SubModel => SubModel,
SubMatrix => SubMatrix,
}
macro_rules! inline {
($($ty:ty => $variant:ident),* $(,)?) => {
pub(crate) fn decode_inline(tag: &str, bytes: &[u8]) -> Result<Root> {
$(
if tag == <$ty as Archivable>::TAG {
let mut value = <$ty as Portable>::from_bytes(bytes)?;
value.on_load();
return Ok(Root::$variant(value));
}
)*
Err(unknown(tag))
}
};
}
inline! {
Mesh => Mesh,
FiniteElementSpace => FiniteElementSpace,
NodeField => NodeField,
ElementField => ElementField,
Evolution => Evolution,
Model => Model,
Matrix => Matrix,
}