Skip to main content

tvm_ffi/
object.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19use std::ops::{Deref, DerefMut};
20use std::sync::atomic::AtomicU64;
21
22use crate::derive::ObjectRef;
23use crate::type_traits::AnyCompatible;
24pub use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
25/// Object related ABI handling
26use tvm_ffi_sys::{TVMFFIAny, TVMFFIGetTypeInfo, TVMFFIObject, COMBINED_REF_COUNT_BOTH_ONE};
27
28/// Held while `#[derive(Object)]` with `#[type_register]` registers a type, so
29/// that registrations from Rust do not race each other: the runtime does not
30/// lock its type table and leaves that to callers.
31#[doc(hidden)]
32pub static TYPE_REGISTRATION: std::sync::Mutex<()> = std::sync::Mutex::new(());
33
34/// Object type is by default the TVMFFIObject
35#[repr(C)]
36pub struct Object {
37    /// example implementation of the object
38    header: TVMFFIObject,
39}
40
41/// Arc-like wrapper for Object that allows shared ownership
42///
43/// \tparam T The type of the object to be wrapped
44#[repr(C)]
45pub struct ObjectArc<T: ObjectCore> {
46    ptr: std::ptr::NonNull<T>,
47    _phantom: std::marker::PhantomData<T>,
48}
49
50unsafe impl<T: Send + Sync + ObjectCore> Send for ObjectArc<T> {}
51unsafe impl<T: Send + Sync + ObjectCore> Sync for ObjectArc<T> {}
52
53/// Traits that can be used to check if a type is an object
54///
55/// This trait is unsafe because it is used to access the object header
56/// and the object header is unsafe to access
57pub unsafe trait ObjectCore: Sized + 'static {
58    /// the type key of the object
59    const TYPE_KEY: &'static str;
60    /// Depth of this type in the object inheritance tree.
61    ///
62    /// The root [`Object`] has depth zero, and every registered subtype has
63    /// depth one greater than its parent. This value must be non-negative and
64    /// agree with the runtime type table entry for `Self`.
65    const TYPE_DEPTH: i32;
66    /// Whether every instance of this type has exactly `Self::type_index()`.
67    ///
68    /// A final type has no separately registered object-system subtype.
69    #[doc(hidden)]
70    const TYPE_FINAL: bool = false;
71    // return the type index of the object
72    fn type_index() -> i32;
73    /// Return the object header
74    /// This function is implemented as a static function so
75    ///
76    /// # Arguments
77    /// * `this` - The object to get the header
78    ///
79    /// # Returns
80    /// * `&mut TVMFFIObject` - The object header
81    /// \return The object header
82    unsafe fn object_header_mut(this: &mut Self) -> &mut TVMFFIObject;
83}
84
85/// Traits for objects with extra items that follows the object
86///
87/// This extra trait can be helpful to implement array types and string types
88pub unsafe trait ObjectCoreWithExtraItems: ObjectCore {
89    /// type of extra items storage that follows the object
90    type ExtraItem;
91    /// Return the number of extra items
92    fn extra_items_count(this: &Self) -> usize;
93    /// Return the extra items data pointer
94    unsafe fn extra_items(this: &Self) -> &[Self::ExtraItem] {
95        let extra_items_ptr = (this as *const Self as *const u8).add(std::mem::size_of::<Self>());
96        std::slice::from_raw_parts(
97            extra_items_ptr as *const Self::ExtraItem,
98            Self::extra_items_count(this),
99        )
100    }
101    /// Return the extra items data pointer
102    unsafe fn extra_items_mut(this: &mut Self) -> &mut [Self::ExtraItem] {
103        let extra_items_ptr = (this as *mut Self as *mut u8).add(std::mem::size_of::<Self>());
104        std::slice::from_raw_parts_mut(
105            extra_items_ptr as *mut Self::ExtraItem,
106            Self::extra_items_count(this),
107        )
108    }
109}
110
111/// Traits to specify core operations of ObjectRef
112///
113/// used by the ffi Any system and not user facing
114///
115/// We mark as unsafe since it moves out the internal of the ObjectRef
116///
117/// # Safety
118///
119/// `data`, `into_data`, and `from_data` must preserve the same object
120/// allocation and form an ownership-preserving round trip. That allocation must
121/// start with a valid `TVMFFIObject` header whose registered object-range
122/// runtime type index correctly describes its layout and inheritance.
123///
124/// When `Self` also implements [`AnyCompatible`], `copy_to_any_view` must
125/// produce a non-owning view, while `move_to_any` must transfer ownership of
126/// the same object pointer and dynamic type index. `move_from_any_after_check`
127/// must be able to reclaim that owned representation exactly once, and a true
128/// `check_any_strict` result must guarantee that both after-check constructors
129/// are valid for it.
130pub unsafe trait ObjectRefCore: Sized + Clone {
131    type ContainerType: ObjectCore;
132    fn data(this: &Self) -> &ObjectArc<Self::ContainerType>;
133    fn into_data(this: Self) -> ObjectArc<Self::ContainerType>;
134
135    /// Construct a reference view from an owning container handle.
136    ///
137    /// # Safety
138    ///
139    /// In addition to containing a valid `ContainerType` allocation, `data`
140    /// must satisfy every semantic invariant imposed by `Self`. This matters
141    /// for zero-state views that share a container type but accept only a
142    /// subset of its values, such as a typed expression view.
143    unsafe fn from_data(data: ObjectArc<Self::ContainerType>) -> Self;
144
145    /// Return whether two object references point to the same allocation.
146    #[inline]
147    fn same_as<Other: ObjectRefCore>(&self, other: &Other) -> bool {
148        unsafe {
149            ObjectArc::as_raw(Self::data(self)).cast::<()>()
150                == ObjectArc::as_raw(Other::data(other)).cast::<()>()
151        }
152    }
153
154    /// Borrow the underlying object as node type `N` when its runtime type matches.
155    ///
156    /// Unlike [`ObjectRefCast::try_cast`], this method neither consumes the
157    /// reference nor changes the object's reference count. The returned node
158    /// cannot outlive `self`.
159    #[inline(always)]
160    fn as_node<N: ObjectCore>(&self) -> Option<&N> {
161        let object = unsafe { ObjectArc::as_raw(Self::data(self)) };
162        let type_index = unsafe { (*object.cast::<TVMFFIObject>()).type_index };
163        if !is_instance_of::<N>(type_index) {
164            return None;
165        }
166        Some(unsafe { &*object.cast::<N>() })
167    }
168}
169
170/// An owning, hashable identity key for an FFI object.
171///
172/// The retained strong reference prevents the allocation address from being
173/// reused while the key is alive. This makes it suitable for identity-based
174/// maps without exposing raw object pointers to downstream code.
175#[derive(Clone)]
176pub struct ObjectIdentity {
177    data: ObjectArc<Object>,
178}
179
180impl ObjectIdentity {
181    /// Retain the allocation referenced by `value` as an identity key.
182    pub fn of<T: ObjectRefCore>(value: &T) -> Self {
183        unsafe {
184            let ptr = ObjectArc::as_raw(T::data(value)) as *mut TVMFFIObject;
185            unsafe_::inc_ref(ptr);
186            Self {
187                data: ObjectArc::from_raw(ptr.cast::<Object>()),
188            }
189        }
190    }
191
192    #[inline]
193    fn as_ptr(&self) -> *const TVMFFIObject {
194        unsafe { ObjectArc::as_raw(&self.data).cast::<TVMFFIObject>() }
195    }
196}
197
198impl PartialEq for ObjectIdentity {
199    #[inline]
200    fn eq(&self, other: &Self) -> bool {
201        self.as_ptr() == other.as_ptr()
202    }
203}
204
205impl Eq for ObjectIdentity {}
206
207impl std::hash::Hash for ObjectIdentity {
208    #[inline]
209    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
210        self.as_ptr().hash(state);
211    }
212}
213
214impl std::fmt::Debug for ObjectIdentity {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        f.debug_tuple("ObjectIdentity")
217            .field(&self.as_ptr())
218            .finish()
219    }
220}
221
222/// Check whether a runtime type index refers to `Target` or one of its
223/// subtypes.
224///
225/// The subtype relation lives in the process-wide type table maintained by the
226/// tvm-ffi library: every registered type records its depth in the single
227/// inheritance tree together with the chain of its ancestors. The check is
228/// O(1) — if `target` really is an ancestor, it must appear in the candidate's
229/// ancestor array exactly at `target`'s depth.
230///
231/// This is a hidden support function for derive-generated object checks. Object
232/// indices in the registered range must refer to entries in the runtime type
233/// table.
234#[doc(hidden)]
235#[inline(always)]
236pub fn is_instance_of<Target: ObjectCore>(object_type_index: i32) -> bool {
237    let target_type_index = Target::type_index();
238    if object_type_index == target_type_index {
239        return true;
240    }
241    // A final type cannot have a separately registered subtype. Keep common
242    // borrowed checks, such as `IntImmObj`, to one integer comparison.
243    if Target::TYPE_FINAL {
244        return false;
245    }
246    let object_begin = TypeIndex::kTVMFFIStaticObjectBegin as i32;
247    // Only object types participate in the type hierarchy.
248    if object_type_index < object_begin || target_type_index < object_begin {
249        return false;
250    }
251    // Parent indices are always smaller than their descendants.
252    if object_type_index < target_type_index {
253        return false;
254    }
255    unsafe {
256        let object_info = TVMFFIGetTypeInfo(object_type_index);
257        if object_info.is_null() {
258            return false;
259        }
260        let target_depth = Target::TYPE_DEPTH;
261        if (*object_info).type_depth <= target_depth {
262            return false;
263        }
264        let ancestor = *(*object_info).type_acenstors.add(target_depth as usize);
265        !ancestor.is_null() && (*ancestor).type_index == target_type_index
266    }
267}
268
269/// Runtime-checked casting between arbitrary `ObjectRef` types.
270///
271/// The cast uses the target's [`AnyCompatible::check_any_strict`] implementation,
272/// mirroring the semantics of `ObjectRef::as<T>` in C++. This supports both
273/// object hierarchies and parameterized object containers.
274///
275/// This trait is blanket-implemented for every [`ObjectRefCore`] type that is
276/// also [`AnyCompatible`].
277pub trait ObjectRefCast: ObjectRefCore + AnyCompatible {
278    /// Consume `self` and rewrap the underlying object as `B` without copying.
279    #[inline(always)]
280    fn try_cast<B>(self) -> crate::error::Result<B>
281    where
282        B: ObjectRefCore + AnyCompatible,
283    {
284        let mut any_data = TVMFFIAny::new();
285        unsafe {
286            // Keep ownership in `self` while the target check runs. This makes
287            // the failure and panic paths unwind normally instead of stranding
288            // an owned object inside a raw TVMFFIAny.
289            Self::copy_to_any_view(&self, &mut any_data);
290            debug_assert!(any_data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32);
291            // SAFETY: ObjectRefCore's contract requires its AnyCompatible
292            // representation to contain a valid object-range type index.
293            std::hint::assert_unchecked(
294                any_data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32,
295            );
296
297            if B::check_any_strict(&any_data) {
298                // Transfer ownership only after the borrowed representation has
299                // passed the target's complete hierarchy/container check.
300                Self::move_to_any(self, &mut any_data);
301                Ok(B::move_from_any_after_check(&mut any_data))
302            } else {
303                let msg = format!(
304                    "Cannot convert from type `{}` to `{}`",
305                    B::get_mismatch_type_info(&any_data),
306                    B::type_str()
307                );
308                Err(crate::error::Error::new(crate::error::TYPE_ERROR, &msg, ""))
309            }
310        }
311    }
312}
313
314impl<T: ObjectRefCore + AnyCompatible> ObjectRefCast for T {}
315
316/// A generic managed reference to a TVM-FFI object.
317///
318/// Holds an `ObjectArc<Object>` that manages the underlying object's lifetime
319/// through reference counting.
320#[repr(C)]
321#[derive(ObjectRef, Clone)]
322pub struct ObjectRef {
323    data: ObjectArc<Object>,
324}
325
326/// Unsafe operations on object
327#[doc(hidden)]
328pub mod unsafe_ {
329    use tvm_ffi_sys::{
330        COMBINED_REF_COUNT_BOTH_ONE, COMBINED_REF_COUNT_MASK_U32, COMBINED_REF_COUNT_STRONG_ONE,
331        COMBINED_REF_COUNT_WEAK_ONE,
332    };
333
334    use std::ffi::c_void;
335    use std::sync::atomic::{fence, Ordering};
336    use tvm_ffi_sys::TVMFFIObject;
337    use tvm_ffi_sys::TVMFFIObjectDeleterFlagBitMask::{
338        kTVMFFIObjectDeleterFlagBitMaskBoth, kTVMFFIObjectDeleterFlagBitMaskStrong,
339        kTVMFFIObjectDeleterFlagBitMaskWeak,
340    };
341
342    /// Increase the strong reference count of the object
343    ///
344    /// This function is same as TVMFFIObjectIncRef but implemented natively in Rust
345    ///
346    /// # Arguments
347    /// * `obj` - The object to increase the reference count
348    #[inline]
349    pub unsafe fn inc_ref(handle: *mut TVMFFIObject) {
350        let obj = &mut *handle;
351        obj.combined_ref_count.fetch_add(1, Ordering::Relaxed);
352    }
353
354    /// Decrease the strong reference count of the object
355    ///
356    /// This function is same as TVMFFIObjectDecRef but implemented natively in Rust
357    ///
358    /// # Arguments
359    /// * `obj` - The object to decrease the reference count
360    #[inline]
361    pub(crate) unsafe fn dec_ref(handle: *mut TVMFFIObject) {
362        let obj = &mut *handle;
363        let old_combined_count = obj
364            .combined_ref_count
365            .fetch_sub(COMBINED_REF_COUNT_STRONG_ONE, Ordering::Relaxed);
366        if old_combined_count == COMBINED_REF_COUNT_BOTH_ONE {
367            if let Some(deleter) = obj.deleter {
368                fence(Ordering::Acquire);
369                deleter(
370                    obj as *mut TVMFFIObject as *mut c_void,
371                    kTVMFFIObjectDeleterFlagBitMaskBoth as i32,
372                );
373            }
374        } else if (old_combined_count & COMBINED_REF_COUNT_MASK_U32)
375            == COMBINED_REF_COUNT_STRONG_ONE
376        {
377            // slow path, there is still a weak reference left
378            // need to run two phase decrement
379            fence(Ordering::Acquire);
380            if let Some(deleter) = obj.deleter {
381                deleter(
382                    obj as *mut TVMFFIObject as *mut c_void,
383                    kTVMFFIObjectDeleterFlagBitMaskStrong as i32,
384                );
385            }
386            let old_weak_count = obj
387                .combined_ref_count
388                .fetch_sub(COMBINED_REF_COUNT_WEAK_ONE, Ordering::Release);
389            if old_weak_count == COMBINED_REF_COUNT_WEAK_ONE {
390                fence(Ordering::Acquire);
391                if let Some(deleter) = obj.deleter {
392                    deleter(
393                        obj as *mut TVMFFIObject as *mut c_void,
394                        kTVMFFIObjectDeleterFlagBitMaskWeak as i32,
395                    );
396                }
397            }
398        }
399    }
400
401    #[inline]
402    pub(crate) unsafe fn strong_count(handle: *mut TVMFFIObject) -> usize {
403        let obj = &mut *handle;
404        (obj.combined_ref_count.load(Ordering::Relaxed) & COMBINED_REF_COUNT_MASK_U32) as usize
405    }
406
407    #[inline]
408    pub(crate) unsafe fn weak_count(handle: *mut TVMFFIObject) -> usize {
409        let obj = &mut *handle;
410        (obj.combined_ref_count.load(Ordering::Relaxed) >> 32) as usize
411    }
412
413    /// Generic object deleter for objects allocated through Rust's global allocator.
414    pub(crate) unsafe extern "C" fn object_deleter_for_new<T>(ptr: *mut c_void, flags: i32)
415    where
416        T: super::ObjectCore,
417    {
418        let obj = ptr as *mut T;
419        if flags & kTVMFFIObjectDeleterFlagBitMaskStrong as i32 != 0 {
420            std::ptr::drop_in_place(obj);
421        }
422        if flags & kTVMFFIObjectDeleterFlagBitMaskWeak as i32 != 0 {
423            std::alloc::dealloc(ptr as *mut u8, std::alloc::Layout::new::<T>());
424        }
425    }
426
427    /// Layout of a `T` followed by `count` extra items, kept at least one word past the
428    /// header: once a weak reference outlives the data, the deleter stores `count` there.
429    pub(crate) fn extra_items_layout<T, U>(count: usize) -> std::alloc::Layout {
430        let size = std::mem::size_of::<T>() + count * std::mem::size_of::<U>();
431        let min_size = std::mem::size_of::<TVMFFIObject>() + std::mem::size_of::<u64>();
432        std::alloc::Layout::from_size_align(size.max(min_size), std::mem::align_of::<T>()).unwrap()
433    }
434
435    pub(crate) unsafe extern "C" fn object_deleter_for_new_with_extra_items<T, U>(
436        ptr: *mut c_void,
437        flags: i32,
438    ) where
439        T: super::ObjectCoreWithExtraItems<ExtraItem = U>,
440    {
441        let obj = ptr as *mut T;
442        if flags == kTVMFFIObjectDeleterFlagBitMaskBoth as i32 {
443            let extra_items_count = T::extra_items_count(&(*obj));
444            std::ptr::drop_in_place(obj);
445            std::alloc::dealloc(
446                ptr as *mut u8,
447                extra_items_layout::<T, U>(extra_items_count),
448            );
449        } else {
450            // Weak references keep using the header, so the weak phase finds the item
451            // count in the first word after it.
452            let count_slot = (ptr as *mut u8).add(std::mem::size_of::<TVMFFIObject>()) as *mut u64;
453            if flags & kTVMFFIObjectDeleterFlagBitMaskStrong as i32 != 0 {
454                let extra_items_count = T::extra_items_count(&(*obj));
455                std::ptr::drop_in_place(obj);
456                std::ptr::write(count_slot, extra_items_count as u64);
457            }
458            if flags & kTVMFFIObjectDeleterFlagBitMaskWeak as i32 != 0 {
459                let extra_items_count = std::ptr::read(count_slot) as usize;
460                std::alloc::dealloc(
461                    ptr as *mut u8,
462                    extra_items_layout::<T, U>(extra_items_count),
463                );
464            }
465        }
466    }
467}
468
469//---------------------
470// Object
471//---------------------
472
473impl Object {
474    pub fn new() -> Self {
475        Self {
476            header: TVMFFIObject::new(),
477        }
478    }
479}
480
481unsafe impl ObjectCore for Object {
482    const TYPE_KEY: &'static str = "ffi.Object";
483    const TYPE_DEPTH: i32 = 0;
484    #[inline]
485    fn type_index() -> i32 {
486        TypeIndex::kTVMFFIStaticObjectBegin as i32
487    }
488    #[inline]
489    unsafe fn object_header_mut(this: &mut Self) -> &mut TVMFFIObject {
490        &mut this.header
491    }
492}
493
494//---------------------
495// ObjectArc
496//---------------------
497
498impl<T: ObjectCore> ObjectArc<T> {
499    pub fn new(data: T) -> Self {
500        unsafe {
501            let layout = std::alloc::Layout::new::<T>();
502            let raw_data_ptr = std::alloc::alloc(layout);
503            if raw_data_ptr.is_null() {
504                std::alloc::handle_alloc_error(layout);
505            }
506            let ptr = raw_data_ptr as *mut T;
507            std::ptr::write(ptr, data);
508            // now override the header directly
509            std::ptr::write(
510                ptr as *mut TVMFFIObject,
511                TVMFFIObject {
512                    combined_ref_count: AtomicU64::new(COMBINED_REF_COUNT_BOTH_ONE),
513                    type_index: T::type_index(),
514                    __padding: 0,
515                    deleter: Some(unsafe_::object_deleter_for_new::<T>),
516                },
517            );
518            // move into the object arc ptr
519            Self {
520                ptr: std::ptr::NonNull::new_unchecked(ptr as *mut T),
521                _phantom: std::marker::PhantomData,
522            }
523        }
524    }
525    pub fn new_with_extra_items<U>(data: T) -> Self
526    where
527        T: ObjectCoreWithExtraItems<ExtraItem = U>,
528    {
529        unsafe {
530            // ensure strict alignment requirements
531            // so we can have { T, U*extra_items } layout
532            assert_eq!(std::mem::align_of::<T>() % std::mem::align_of::<U>(), 0);
533            assert_eq!(std::mem::size_of::<T>() % std::mem::align_of::<U>(), 0);
534            let extra_items_count = T::extra_items_count(&data);
535            let layout = unsafe_::extra_items_layout::<T, U>(extra_items_count);
536            let raw_data_ptr = std::alloc::alloc(layout);
537            if raw_data_ptr.is_null() {
538                std::alloc::handle_alloc_error(layout);
539            }
540            let ptr = raw_data_ptr as *mut T;
541            std::ptr::write(ptr, data);
542            // now override the header directly
543            std::ptr::write(
544                ptr as *mut TVMFFIObject,
545                TVMFFIObject {
546                    combined_ref_count: AtomicU64::new(COMBINED_REF_COUNT_BOTH_ONE),
547                    type_index: T::type_index(),
548                    __padding: 0,
549                    deleter: Some(unsafe_::object_deleter_for_new_with_extra_items::<T, U>),
550                },
551            );
552            // move into the object arc ptr
553            Self {
554                ptr: std::ptr::NonNull::new_unchecked(ptr as *mut T),
555                _phantom: std::marker::PhantomData,
556            }
557        }
558    }
559
560    /// Whether `this` holds a null pointer, as all-zero bytes do: no
561    /// `ObjectArc`, but the field of an object that a creator left undefined.
562    ///
563    /// # Safety
564    ///
565    /// `this` points to an `ObjectArc<T>` or to all-zero bytes.
566    #[doc(hidden)]
567    #[inline]
568    pub unsafe fn is_null(this: *const Self) -> bool {
569        (*std::ptr::addr_of!((*this).ptr).cast::<*const T>()).is_null()
570    }
571
572    /// Move a previously allocated object into the ObjectArc
573    ///
574    /// # Arguments
575    /// * `ptr` - The raw pointer to move into the ObjectArc
576    ///
577    /// # Returns
578    /// * `ObjectArc<T>` - The ObjectArc
579    /// \return The ObjectArc
580    #[inline]
581    pub unsafe fn from_raw(ptr: *const T) -> Self {
582        Self {
583            ptr: std::ptr::NonNull::new_unchecked(ptr as *mut T),
584            _phantom: std::marker::PhantomData,
585        }
586    }
587
588    /// Move the ObjectArc into a raw pointer
589    ///
590    /// # Arguments
591    /// * `this` - The ObjectArc to move into a raw pointer
592    ///
593    /// # Returns
594    /// * `*const T` - The raw pointer
595    #[inline]
596    pub unsafe fn into_raw(this: Self) -> *const T {
597        let droped_this = std::mem::ManuallyDrop::new(this);
598        droped_this.ptr.as_ptr() as *const T
599    }
600
601    /// Get the raw pointer from the ObjectArc
602    ///
603    /// Caller should view this as a non-owning reference
604    ///
605    /// # Arguments
606    /// * `this` - The ObjectArc to get the raw pointer
607    ///
608    /// # Returns
609    /// * `*const T` - The raw pointer
610    /// \return The raw pointer
611    #[inline]
612    pub unsafe fn as_raw(this: &Self) -> *const T {
613        this.ptr.as_ptr() as *const T
614    }
615
616    /// Get the raw mutable pointer from the ObjectArc
617    ///
618    /// Caller should view this as a non-owning reference
619    ///
620    /// # Arguments
621    /// * `this` - The ObjectArc to get the raw pointer
622    ///
623    /// # Returns
624    /// * `*mut T` - The raw pointer
625    #[inline]
626    pub unsafe fn as_raw_mut(this: &mut Self) -> *mut T {
627        this.ptr.as_mut()
628    }
629
630    /// Get the strong reference count of the ObjectArc
631    ///
632    /// # Arguments
633    /// * `this` - The ObjectArc to get the strong reference count
634    ///
635    /// # Returns
636    /// * `usize` - The strong reference count
637    #[inline]
638    pub fn strong_count(this: &Self) -> usize {
639        unsafe {
640            unsafe_::strong_count(this.ptr.as_ref() as *const T as *mut T as *mut TVMFFIObject)
641        }
642    }
643
644    /// Get the weak reference count of the ObjectArc
645    ///
646    /// # Arguments
647    /// * `this` - The ObjectArc to get the weak reference count
648    ///
649    /// # Returns
650    /// * `usize` - The weak reference count
651    #[inline]
652    pub fn weak_count(this: &Self) -> usize {
653        unsafe { unsafe_::weak_count(this.ptr.as_ref() as *const T as *mut T as *mut TVMFFIObject) }
654    }
655}
656
657// implement Deref for ObjectArc
658impl<T: ObjectCore> Deref for ObjectArc<T> {
659    type Target = T;
660    #[inline]
661    fn deref(&self) -> &Self::Target {
662        unsafe { self.ptr.as_ref() }
663    }
664}
665
666// implement DerefMut for ObjectArc
667impl<T: ObjectCore> DerefMut for ObjectArc<T> {
668    #[inline]
669    fn deref_mut(&mut self) -> &mut Self::Target {
670        unsafe { self.ptr.as_mut() }
671    }
672}
673
674// implement Drop for ObjectArc
675impl<T: ObjectCore> Drop for ObjectArc<T> {
676    fn drop(&mut self) {
677        unsafe { unsafe_::dec_ref(self.ptr.as_mut() as *mut T as *mut TVMFFIObject) }
678    }
679}
680
681// implement Clone for ObjectArc
682impl<T: ObjectCore> Clone for ObjectArc<T> {
683    #[inline]
684    fn clone(&self) -> Self {
685        unsafe { unsafe_::inc_ref(self.ptr.as_ref() as *const T as *mut T as *mut TVMFFIObject) }
686        Self {
687            ptr: self.ptr,
688            _phantom: std::marker::PhantomData,
689        }
690    }
691}