Skip to main content

tvm_ffi/
rvalue_ref.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 */
19
20//! [`RValueRef`], an object argument whose reference the callee may take over.
21
22use std::cell::UnsafeCell;
23use std::marker::PhantomData;
24
25use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject, TVMFFITypeIndex as TypeIndex};
26
27use crate::any::ArgTryFromAnyView;
28use crate::{AnyView, Error, ObjectRefCore, Result};
29
30/// An object argument that the callee may move out of, as `ffi::RValueRef<T>`
31/// in the ABI.
32///
33/// The callee may take the stored strong reference without incrementing its
34/// count. If it does not, the wrapper keeps the reference and releases it when
35/// dropped.
36pub struct RValueRef<T>
37where
38    T: ObjectRefCore,
39{
40    slot: UnsafeCell<*mut TVMFFIObject>,
41    _marker: PhantomData<T>,
42}
43
44impl<T> RValueRef<T>
45where
46    T: ObjectRefCore,
47{
48    /// Transfer an owned object reference into an rvalue argument slot.
49    pub fn new(value: T) -> Self {
50        let mut raw = TVMFFIAny::new();
51        unsafe { T::move_to_any(value, &mut raw) };
52        debug_assert!(raw.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32);
53        Self {
54            slot: UnsafeCell::new(unsafe { raw.data_union.v_obj }),
55            _marker: PhantomData,
56        }
57    }
58
59    /// Take the owned object without copying or incrementing its reference count.
60    ///
61    /// # Panics
62    ///
63    /// Panics if the object was already taken, such as by a callee that moved
64    /// it out of the argument slot.
65    pub fn into_inner(mut self) -> T {
66        let object = *self.slot.get_mut();
67        assert!(!object.is_null(), "RValueRef has already been moved");
68        *self.slot.get_mut() = std::ptr::null_mut();
69        unsafe {
70            let mut raw = object_any(object);
71            T::move_from_any_after_check(&mut raw)
72        }
73    }
74
75    unsafe fn from_view(value: &AnyView<'_>, arg_index: Option<usize>) -> Result<Self> {
76        let raw = value.as_raw_ffi_any();
77        let converted = if raw.type_index == TypeIndex::kTVMFFIObjectRValueRef as i32 {
78            let slot = unsafe { raw.data_union.v_ptr.cast::<*mut TVMFFIObject>() };
79            if slot.is_null() || unsafe { (*slot).is_null() } {
80                return Err(unsafe { conversion_error::<T>(raw, arg_index, true) });
81            }
82            let object = unsafe { *slot };
83            let object_view = unsafe { object_any(object) };
84            if unsafe { T::check_any_strict(&object_view) } {
85                unsafe { *slot = std::ptr::null_mut() };
86                return Ok(Self {
87                    slot: UnsafeCell::new(object),
88                    _marker: PhantomData,
89                });
90            }
91            unsafe { T::try_cast_from_any_view(&object_view) }
92        } else if unsafe { T::check_any_strict(raw) } {
93            Ok(unsafe { T::copy_from_any_view_after_check(raw) })
94        } else {
95            unsafe { T::try_cast_from_any_view(raw) }
96        };
97
98        converted
99            .map(Self::new)
100            .map_err(|()| unsafe { conversion_error::<T>(raw, arg_index, false) })
101    }
102}
103
104impl<T> From<T> for RValueRef<T>
105where
106    T: ObjectRefCore,
107{
108    fn from(value: T) -> Self {
109        Self::new(value)
110    }
111}
112
113impl<'a, T> From<&'a RValueRef<T>> for AnyView<'a>
114where
115    T: ObjectRefCore,
116{
117    fn from(value: &'a RValueRef<T>) -> Self {
118        let mut raw = TVMFFIAny::new();
119        raw.type_index = TypeIndex::kTVMFFIObjectRValueRef as i32;
120        raw.data_union.v_ptr = value.slot.get().cast();
121        unsafe { AnyView::from_raw_ffi_any(raw) }
122    }
123}
124
125impl<T> TryFrom<AnyView<'_>> for RValueRef<T>
126where
127    T: ObjectRefCore,
128{
129    type Error = Error;
130
131    fn try_from(value: AnyView<'_>) -> Result<Self> {
132        unsafe { Self::from_view(&value, None) }
133    }
134}
135
136impl<T> crate::type_traits::TypeSchema for RValueRef<T>
137where
138    T: ObjectRefCore,
139{
140    fn type_schema() -> std::string::String {
141        crate::type_traits::type_schema("ObjectRValueRef", &[T::type_schema()])
142    }
143}
144
145impl<T> ArgTryFromAnyView for RValueRef<T>
146where
147    T: ObjectRefCore,
148{
149    fn try_from_any_view(value: &AnyView<'_>, arg_index: usize) -> Result<Self> {
150        unsafe { Self::from_view(value, Some(arg_index)) }
151    }
152}
153
154impl<T> Drop for RValueRef<T>
155where
156    T: ObjectRefCore,
157{
158    fn drop(&mut self) {
159        let object = *self.slot.get_mut();
160        if !object.is_null() {
161            unsafe { crate::object::unsafe_::dec_ref(object) };
162        }
163    }
164}
165
166/// Reconstruct the owned object's ABI representation.
167///
168/// # Safety
169/// `object` must point to a live managed object with a registered object-range
170/// dynamic type index.
171unsafe fn object_any(object: *mut TVMFFIObject) -> TVMFFIAny {
172    let mut raw = TVMFFIAny::new();
173    raw.type_index = unsafe { (*object).type_index };
174    // SAFETY: The caller provides a live object from an owning reference or
175    // a valid object-rvalue slot, so its dynamic type is in the object range.
176    unsafe {
177        core::hint::assert_unchecked(raw.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32)
178    };
179    raw.data_union.v_obj = object;
180    raw
181}
182
183unsafe fn conversion_error<T>(
184    raw: &TVMFFIAny,
185    arg_index: Option<usize>,
186    already_moved: bool,
187) -> Error
188where
189    T: ObjectRefCore,
190{
191    let source = if already_moved {
192        "an already-moved RValueRef".to_string()
193    } else if raw.type_index == TypeIndex::kTVMFFIObjectRValueRef as i32 {
194        "RValueRef with an incompatible object type".to_string()
195    } else {
196        T::get_mismatch_type_info(raw)
197    };
198    let prefix = arg_index
199        .map(|index| format!("Argument #{index}: "))
200        .unwrap_or_default();
201    Error::new(
202        crate::error::TYPE_ERROR,
203        &format!(
204            "{prefix}Cannot convert from `{source}` to `RValueRef<{}>`",
205            T::type_str()
206        ),
207    )
208}