use std::collections::HashMap;
use bstack::BStack;
use crate::primitives::{EightCC, OwnershipKind, WidePtr};
use crate::util::read_u64;
use super::RttiResult;
use super::{
FOREIGN_REPR_LEN, RttiOrdinal, RttiRegistry, RttiType, Shape, VECDESC_LEN, add_off, mul_off,
unknown_tag,
};
impl Shape {
pub(in crate::rtti) fn has_reference(&self) -> bool {
match self {
Shape::Pod { .. } | Shape::Class { .. } => false,
Shape::Owned(_)
| Shape::Strong(_)
| Shape::Weak(_)
| Shape::Ref(_)
| Shape::Embed(_)
| Shape::Foreign { .. } => true,
Shape::Option(inner) | Shape::Vec(inner) | Shape::Array { inner, .. } => {
inner.has_reference()
}
Shape::Tuple(items) => items.iter().any(Shape::has_reference),
}
}
pub(in crate::rtti) fn element_ref_tag(&self) -> Option<EightCC> {
match self {
Shape::Owned(t) | Shape::Strong(t) | Shape::Weak(t) | Shape::Ref(t) => Some(*t),
Shape::Option(inner) => inner.element_ref_tag(),
_ => None,
}
}
pub(in crate::rtti) fn weak_element_tag(&self) -> Option<EightCC> {
match self {
Shape::Weak(t) => Some(*t),
Shape::Option(inner) => inner.weak_element_tag(),
_ => None,
}
}
pub(in crate::rtti) fn foreign_leaf(&self) -> Option<(EightCC, OwnershipKind)> {
match self {
Shape::Foreign { tag, kind } => Some((*tag, *kind)),
Shape::Option(inner) => inner.foreign_leaf(),
_ => None,
}
}
pub(in crate::rtti) fn option_present(&self, data: &BStack, base: u64) -> RttiResult<bool> {
Ok(match self {
Shape::Foreign { .. } => !WidePtr::read_from_stack(data, base)?.is_null(),
_ => read_u64(data, base)? != 0,
})
}
pub(in crate::rtti) fn peel_option(&self) -> &Shape {
match self {
Shape::Option(inner) => inner.peel_option(),
other => other,
}
}
pub(in crate::rtti) fn is_vec_element_leaf(&self) -> bool {
matches!(
self.peel_option(),
Shape::Pod { .. }
| Shape::Ref(_)
| Shape::Owned(_)
| Shape::Strong(_)
| Shape::Weak(_)
| Shape::Foreign { .. }
)
}
}
impl RttiRegistry {
pub(in crate::rtti) fn shape_stride(
&self,
shape: &Shape,
cache: &mut HashMap<RttiOrdinal, RttiType>,
) -> RttiResult<u64> {
Ok(match shape {
Shape::Pod { width } => *width as u64,
Shape::Owned(_) | Shape::Strong(_) | Shape::Weak(_) | Shape::Ref(_) => 8,
Shape::Foreign { .. } => FOREIGN_REPR_LEN,
Shape::Vec(_) => VECDESC_LEN,
Shape::Option(inner) => self.shape_stride(inner, cache)?,
Shape::Array { n, inner } => mul_off(*n as u64, self.shape_stride(inner, cache)?)?,
Shape::Tuple(items) => {
let mut sum = 0u64;
for it in items {
sum = add_off(sum, self.shape_stride(it, cache)?)?;
}
sum
}
Shape::Embed(tag) => {
let ord = self.ordinal_of(*tag).ok_or_else(unknown_tag)?;
if let std::collections::hash_map::Entry::Vacant(e) = cache.entry(ord) {
e.insert(self.load_type(ord)?);
}
cache[&ord].ondisk_size
}
Shape::Class { .. } => 0,
})
}
}