Skip to main content

impl_object_ref_upcast

Macro impl_object_ref_upcast 

Source
macro_rules! impl_object_ref_upcast {
    (unsafe $($source:ty => $target:ty),+ $(,)?) => { ... };
    ($($source:ty => $target:ty),+ $(,)?) => { ... };
}
Expand description

Implement zero-copy conversions from a derived object reference to one of its base object-reference types: From<Source> and From<&Source> into Target, AsRef<Target>, which borrows a &Source as &Target without touching the reference count, and IntoArg<Target> for Source and &Source, and TypeSubsumes<Source> for Target, so Array::upcast turns an Array<Source> into an Array<Target>. It also implements the strict downcast back, TryFrom<Target> and TryFrom<&Target> for Source, which return a TypeError naming both types.

impl_object_ref_upcast!(Add => BinaryOp, Add => Expr); checks at compile time that the object type of Source derives from that of Target (ObjectDerivesFrom), and that Target accepts every object of its type, as a non-generic #[derive(ObjectRef)] reference does.

ยงSafety

For a Target that promises more than its object type, such as a generic reference or one with a custom ObjectRefAnyCompatible, write impl_object_ref_upcast!(unsafe Add => PrimExpr);. The leading unsafe skips both checks: writing it, the caller promises that Target is a base of Source and every Source satisfies the Target invariants. An incorrect declaration makes the generated safe conversions unsound.