Seven-Streams opened a new pull request, #684:
URL: https://github.com/apache/tvm-ffi/pull/684
# [Rust][Feat] Add runtime-checked casting between ObjectRef types
## Summary
Add runtime-checked casting between arbitrary `ObjectRef` types in the Rust
bindings, mirroring C++ `ObjectRef::as<T>` / `Downcast<T>`.
- **`ObjectRefCast`** (blanket impl for all `ObjectRefCore` types):
- `try_cast::<B>(self)` — consumes `self`, rewraps the object pointer
without
copying; fails with a `TypeError` naming both type keys.
- `cast_clone::<B>(&self)` — borrowing variant, shares ownership via
inc_ref.
- Succeeds iff the **runtime** type of the underlying object is
`B::ContainerType` or a subtype, so downcasting through a parent
reference
works as expected.
```rust
let base: TestBase = derived.try_cast()?; // upcast
let obj: ObjectRef = base.try_cast()?; // upcast to root
let d: TestDerived = obj.try_cast()?; // checked downcast
```
- **`is_instance_of(a_idx, b_idx)`** — O(1) subtype check via the
process-wide
type table (equal-index fast path + one ancestor-table lookup), the Rust
counterpart of C++ `IsObjectInstance`.
- **Hierarchy-aware `Any`/`AnyView` conversions**: derive-generated
`check_any_strict` / `try_cast_from_any_view` now use `is_instance_of`,
aligning with C++ `CheckAnyStrict` — converting an `Any` holding a derived
object to a parent reference (incl. `ObjectRef`) now succeeds.
- **Derive fixes** (uncovered by first external-crate use): generated code no
longer references `proc_macro_error`; `type_str()` return type fully
qualified; `object::unsafe_` made `#[doc(hidden)] pub`.
- **Tests**: `tests/test_cast.rs` covers multi-level up/downcast round-trips,
failure messages, refcounts, `Any` subtype conversions/rejections, and
leak-free destruction. Exact-match fast path unchanged (~1 compare); slow
path ~8ns, only on previously-failing paths.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]