Skip to main content

ObjectRef

Derive Macro ObjectRef 

#[derive(ObjectRef)]
{
    // Attributes available to this derive:
    #[object_ref]
}
Expand description

Declare an object reference: the managed, reference-counted handle to an object type, as Arc<FooObj> is to FooObj.

The struct holds one field, ObjectArc<FooObj>. The derive implements ObjectRefCore, the default ObjectRefAnyCompatible (conversions to and from Any, in-place downcasts, typed function arguments), the upcast to ObjectRef, Deref<Target = FooObj> for field reads, Debug, Display (the runtime repr, as AnyView formats it), and a private fn from_object(object: FooObj) -> Self for the type’s constructors.

§Options

#[object_ref(...)] takes:

  • parent = Ref - The reference to the parent’s object, or to a further ancestor’s; Self converts into it. The object type must embed that object type through its chain of parents (ObjectDerivesFrom), so a wrong parent does not compile. Any other ancestor takes impl_object_ref_upcast!.
  • unsafe parent = Ref - As parent, for a reference that promises more than its object type: a generic one (Array<T>, Map<K, V>, Optional<T>) or one with a custom ObjectRefAnyCompatible. The caller promises that every value of Self is a valid Ref; parent alone does not compile for such a reference.
  • skip_deref - No Deref, for a reference whose object is internal.
  • skip_debug - Debug is written by hand.
  • skip_display - Display is written by hand.
  • skip_any_compatible - ObjectRefAnyCompatible is written by hand, for a typed reference with a stricter check or fallback conversions.
  • crate = path - Where the generated code finds tvm-ffi, as for rs_object.

§Examples

use tvm_ffi::derive::ObjectRef;
use tvm_ffi::{rs_object, Object, ObjectArc};

#[rs_object(type_key = "my_ext.MyPair")]
pub struct MyPairObj {
    base_: Object,
    pub first: i64,
    pub second: i64,
}

#[derive(Clone, ObjectRef)]
pub struct MyPair {
    data: ObjectArc<MyPairObj>,
}

#[rs_object(type_key = "my_ext.MyTriple", final)]
pub struct MyTripleObj {
    base_: MyPairObj,
    pub third: i64,
}

#[derive(Clone, ObjectRef)]
#[object_ref(parent = MyPair)]
pub struct MyTriple {
    data: ObjectArc<MyTripleObj>,
}

impl MyTriple {
    pub fn new(first: i64, second: i64, third: i64) -> Self {
        let pair = MyPairObj::new(Object::new(), first, second);
        Self::from_object(MyTripleObj::new(pair, third))
    }
}

let triple = MyTriple::new(1, 2, 3);
assert_eq!(triple.first + triple.third, 4);
let _pair: MyPair = triple.into();

A MyPairObj does not embed an ArrayObj, so it cannot claim Array as its parent:

ⓘ
use tvm_ffi::derive::ObjectRef;
use tvm_ffi::{rs_object, Array, Object, ObjectArc};

#[rs_object(type_key = "my_ext.MyPair")]
pub struct MyPairObj {
    base_: Object,
    pub first: i64,
}

#[derive(Clone, ObjectRef)]
#[object_ref(unsafe parent = Array<i64>)]
pub struct MyPair {
    data: ObjectArc<MyPairObj>,
}