Skip to main content

tvm_ffi/
optional.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//! [`Optional<T>`], an optional value that is not an object, such as a scalar
20//! or a string, stored in place.
21//!
22//! It is one 16-byte `TVMFFIAny` cell holding the value or `None`, the ABI
23//! layout of an optional non-object value in every language. An optional
24//! object is one nullable pointer, which [`std::option::Option<X>`] already
25//! is, so `Optional<X>` of an object type is rejected at compile time.
26//!
27//! A reflected field holding an optional non-object value is an `Optional<T>`;
28//! an `Option<T>` there is rejected at registration, since it is laid out as
29//! neither form.
30
31use crate::any::Any;
32use crate::string::{Bytes, String};
33use crate::type_traits::AnyCompatible;
34use std::fmt::{self, Debug};
35use std::marker::PhantomData;
36use tvm_ffi_sys::TVMFFIAny;
37
38/// Marker for the types whose optional the ABI stores as one 16-byte
39/// `TVMFFIAny` cell, the types [`Optional<T>`] accepts.
40///
41/// Object types deliberately do not implement it: use `Option<X>`, one
42/// nullable pointer, for those.
43///
44/// # Safety
45/// Implement only for types whose optional the ABI stores as a `TVMFFIAny`
46/// cell; for an object type it would mismatch the ABI's nullable pointer.
47///
48/// ```compile_fail,E0277
49/// use tvm_ffi::{Array, Optional};
50/// let _ = Optional::<Array<i64>>::none();
51/// ```
52#[diagnostic::on_unimplemented(
53    message = "`Optional<{Self}>` only mirrors non-object-pointer `ffi::Optional` values",
54    label = "`{Self}` uses the object-pointer optional representation",
55    note = "use `Option<{Self}>` for object classes; it is the compatible nullable-pointer layout"
56)]
57pub unsafe trait OptionalCompatible: AnyCompatible {}
58
59macro_rules! impl_optional_compatible {
60    ($($t:ty),* $(,)?) => {
61        $(unsafe impl OptionalCompatible for $t {})*
62    };
63}
64
65impl_optional_compatible!(
66    bool,
67    i8,
68    i16,
69    i32,
70    i64,
71    isize,
72    u8,
73    u16,
74    u32,
75    u64,
76    usize,
77    f32,
78    f64,
79    *mut core::ffi::c_void,
80    crate::DLDataType,
81    crate::DLDevice,
82    String,
83    Bytes,
84    crate::big_int::BigInt,
85);
86
87/// An optional value that is not an object, stored in place as one 16-byte
88/// cell holding the value or `None`. See the [module docs](self).
89#[repr(transparent)]
90pub struct Optional<T: OptionalCompatible> {
91    // Holds either the value's `TVMFFIAny` representation or a `kTVMFFINone` cell.
92    data: Any,
93    _marker: PhantomData<T>,
94}
95
96// SAFETY: the cell holds only a `T` or `None`, so sending or sharing an
97// `Optional` is as safe as sending or sharing its value.
98unsafe impl<T: OptionalCompatible + Send + Sync> Send for Optional<T> {}
99unsafe impl<T: OptionalCompatible + Send + Sync> Sync for Optional<T> {}
100
101// Must stay 16 bytes / `TVMFFIAny`-aligned to overlay a C++ `ffi::Optional<T>`
102// field in place, independent of `T`.
103const _: () = assert!(
104    std::mem::size_of::<Optional<i64>>() == 16
105        && std::mem::size_of::<Optional<String>>() == 16
106        && std::mem::align_of::<Optional<i64>>()
107            == std::mem::align_of::<crate::tvm_ffi_sys::TVMFFIAny>()
108);
109
110impl<T: OptionalCompatible> Optional<T> {
111    /// An optional holding `value`.
112    #[inline]
113    pub fn some(value: T) -> Self {
114        Self {
115            data: Any::from(value),
116            _marker: PhantomData,
117        }
118    }
119
120    /// An empty optional, holding `None`.
121    #[inline]
122    pub fn none() -> Self {
123        Self {
124            data: Any::new(),
125            _marker: PhantomData,
126        }
127    }
128
129    /// Whether a value is present.
130    #[inline]
131    pub fn is_some(&self) -> bool {
132        !self.data.is_none()
133    }
134
135    /// Whether the optional is empty.
136    #[inline]
137    pub fn is_none(&self) -> bool {
138        !self.is_some()
139    }
140
141    /// Returns a clone of the value, or `None` when empty.
142    #[inline]
143    pub fn get(&self) -> Option<T> {
144        // Strict: the value comes back exactly as stored, never converted.
145        let cell = self.data.as_raw_ffi_any();
146        // SAFETY: the cell is valid while `self` is borrowed, and the copy
147        // runs only after the strict check.
148        unsafe { T::check_any_strict(cell).then(|| T::copy_from_any_view_after_check(cell)) }
149    }
150
151    /// Takes the value out, without cloning it.
152    #[inline]
153    pub fn into_option(self) -> Option<T> {
154        if self.is_some() {
155            // Move the value out of the owning `Any` without dropping it, then
156            // transfer ownership of the payload into `T` (no inc/dec ref).
157            let mut raw = Any::into_raw_ffi_any(self.data);
158            Some(unsafe { T::move_from_any_after_check(&mut raw) })
159        } else {
160            None
161        }
162    }
163
164    /// Replaces the value, dropping the previous one.
165    #[inline]
166    pub fn set(&mut self, value: Option<T>) {
167        // Assignment drops the old `Any` (dec_ref if object) before storing the new.
168        self.data = match value {
169            Some(v) => Any::from(v),
170            None => Any::new(),
171        };
172    }
173}
174
175impl<T: OptionalCompatible + crate::type_traits::RefFromAnyUnchecked> Optional<T> {
176    /// Borrow the value in place, like [`Option::as_ref`].
177    ///
178    /// Available for values the cell stores as themselves, such as `String`,
179    /// `i64` and `f64`; use [`get`](Self::get) for the others.
180    ///
181    /// # Returns
182    ///
183    /// The borrowed value, or `None` when empty.
184    ///
185    /// ```
186    /// use tvm_ffi::Optional;
187    /// let value = Optional::some(7_i64);
188    /// assert_eq!(value.as_ref(), Some(&7));
189    /// assert_eq!(Optional::<i64>::none().as_ref(), None);
190    /// ```
191    #[inline]
192    pub fn as_ref(&self) -> Option<&T> {
193        if self.is_some() {
194            // SAFETY: an engaged `Optional<T>` cell holds a `T`.
195            Some(unsafe { T::ref_from_any_unchecked(self.data.as_raw_ffi_any()) })
196        } else {
197            None
198        }
199    }
200}
201
202impl Optional<String> {
203    /// Borrows the string as `&str`, or `None` when empty.
204    #[inline]
205    pub fn as_str(&self) -> Option<&str> {
206        if self.is_some() {
207            // SAFETY: an engaged `Optional<String>` cell is byte-identical to a
208            // `String` (both are `#[repr(C)]` with the 16-byte cell as their only field),
209            // and the borrow is tied to `&self`.
210            let s = unsafe { &*(&self.data as *const Any as *const String) };
211            Some(s.as_str())
212        } else {
213            None
214        }
215    }
216}
217
218// Converts as `Option<T>` does; the cell itself is the `Any` form, which makes
219// `Optional<T>` a reflected field laid out as C++ `ffi::Optional<T>`.
220unsafe impl<T: OptionalCompatible> AnyCompatible for Optional<T> {
221    fn type_str() -> std::string::String {
222        Option::<T>::type_str()
223    }
224
225    fn type_schema() -> std::string::String {
226        Option::<T>::type_schema()
227    }
228
229    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
230        *data = *src.data.as_raw_ffi_any();
231    }
232
233    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
234        *data = Any::into_raw_ffi_any(src.data);
235    }
236
237    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
238        unsafe { Option::<T>::check_any_strict(data) }
239    }
240
241    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
242        unsafe { Option::<T>::match_constraints(data) }
243    }
244
245    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
246        unsafe { Option::<T>::copy_from_any_view_after_check(data).into() }
247    }
248
249    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
250        unsafe { Option::<T>::move_from_any_after_check(data).into() }
251    }
252
253    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
254        unsafe { Option::<T>::try_cast_from_any_view(data).map(Self::from) }
255    }
256}
257
258crate::impl_into_arg!(impl[T: OptionalCompatible] Optional<T>);
259
260impl<T: OptionalCompatible> Default for Optional<T> {
261    /// The empty optional, holding `None`.
262    #[inline]
263    fn default() -> Self {
264        Self::none()
265    }
266}
267
268impl<T: OptionalCompatible> Clone for Optional<T> {
269    #[inline]
270    fn clone(&self) -> Self {
271        Self {
272            // `Any::clone` inc_refs an object payload; a `nullopt` cell is a no-op.
273            data: self.data.clone(),
274            _marker: PhantomData,
275        }
276    }
277}
278
279impl<T: OptionalCompatible + PartialEq> PartialEq for Optional<T> {
280    #[inline]
281    fn eq(&self, other: &Self) -> bool {
282        self.get() == other.get()
283    }
284}
285
286impl<T: OptionalCompatible + Eq> Eq for Optional<T> {}
287
288impl<T: OptionalCompatible> From<Option<T>> for Optional<T> {
289    #[inline]
290    fn from(value: Option<T>) -> Self {
291        match value {
292            Some(v) => Self::some(v),
293            None => Self::none(),
294        }
295    }
296}
297
298impl<T: OptionalCompatible> From<Optional<T>> for Option<T> {
299    #[inline]
300    fn from(value: Optional<T>) -> Self {
301        value.into_option()
302    }
303}
304
305impl<T: OptionalCompatible + Debug> Debug for Optional<T> {
306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307        match self.get() {
308            Some(v) => write!(f, "Optional::Some({v:?})"),
309            None => f.write_str("Optional::None"),
310        }
311    }
312}