Skip to main content

tvm_ffi/extra/
unchanged.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//! Typed unchanged-or-replacement results for structural mutation.
21
22use std::marker::PhantomData;
23
24use super::structural_common::{raw_ffi_any_same_as, structural_error_from_raw};
25
26use crate::any::{Any, AnyView, TryFromTemp};
27use crate::error::{Error, Result};
28use crate::tvm_ffi_sys::{TVMFFIAny, TVMFFITypeIndex};
29use crate::type_traits::{AnyCompatible, ContainerElement};
30
31/// A marker result that keeps the original value.
32///
33/// A map or mutation callback returns `Unchanged`, usually as
34/// `Unchanged.into()`, to keep the value it was given without retaining or
35/// cloning it. A pre-order map still descends into the original value's
36/// children.
37///
38/// # Examples
39///
40/// ```
41/// use tvm_ffi::{Any, Unchanged, UnchangedOr};
42///
43/// let result: UnchangedOr<Any> = Unchanged.into();
44/// assert!(result.is_unchanged());
45/// ```
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47pub struct Unchanged;
48
49/// Either a replacement value of type `T`, or [`Unchanged`] to keep the
50/// original.
51///
52/// Structural map and mutation callbacks return `Result<UnchangedOr<Any>>`.
53/// It is like `Option<T>` whose `None` means "keep what was there", stored in
54/// one FFI value. `UnchangedOr<Any>` converts with `.into()` from
55/// [`Unchanged`], from a managed reference or scalar, and from a typed
56/// `UnchangedOr<T>`. `T` is an FFI value type or [`Any`]. Converting the
57/// wrapper into `Any` keeps the marker; use [`value_or_unchanged`](Self::value_or_unchanged) or
58/// [`into_option`](Self::into_option) when an actual value is needed.
59///
60/// # Examples
61///
62/// ```
63/// use tvm_ffi::UnchangedOr;
64///
65/// fn double_even(value: i64) -> UnchangedOr<i64> {
66///     if value % 2 == 0 {
67///         UnchangedOr::changed(value * 2)
68///     } else {
69///         UnchangedOr::unchanged()
70///     }
71/// }
72///
73/// assert_eq!(double_even(4).value_or_unchanged(4), 8);
74/// assert_eq!(double_even(3).value_or_unchanged(3), 3);
75/// ```
76#[repr(transparent)]
77pub struct UnchangedOr<T: ContainerElement = Any> {
78    data: Any,
79    _marker: PhantomData<T>,
80}
81
82impl<T: ContainerElement> UnchangedOr<T> {
83    /// Create a result that keeps the original value, without borrowing or cloning
84    /// it.
85    ///
86    /// # Returns
87    ///
88    /// An unchanged result.
89    #[inline]
90    pub fn unchanged() -> Self {
91        Self {
92            data: Unchanged.into(),
93            _marker: PhantomData,
94        }
95    }
96
97    /// Create a result that replaces the original value.
98    ///
99    /// # Arguments
100    ///
101    /// * `value` - The replacement.
102    ///
103    /// # Returns
104    ///
105    /// A result holding `value`.
106    #[inline]
107    pub fn changed(value: T) -> Self {
108        let mut raw = TVMFFIAny::new();
109        // SAFETY: ContainerElement transfers exactly one owning value.
110        unsafe {
111            T::container_move_to_any(value, &mut raw);
112            Self {
113                data: Any::from_raw_ffi_any(raw),
114                _marker: PhantomData,
115            }
116        }
117    }
118
119    /// Return whether this result keeps the original value.
120    ///
121    /// # Returns
122    ///
123    /// `true` if the result is unchanged.
124    #[inline]
125    pub fn is_unchanged(&self) -> bool {
126        is_unchanged(&self.data)
127    }
128
129    /// Return whether this result is unchanged or holds `original` itself.
130    ///
131    /// An object counts as the same only when it is the same object, not an equal
132    /// copy. Use it to tell whether anything was rewritten.
133    ///
134    /// # Arguments
135    ///
136    /// * `original` - The original value.
137    ///
138    /// # Returns
139    ///
140    /// `true` if the result is unchanged or holds `original`.
141    ///
142    /// ```
143    /// use tvm_ffi::{Array, UnchangedOr};
144    /// let original = Array::from_vec(vec![1_i64]);
145    /// assert!(UnchangedOr::changed(original.clone()).unchanged_or_same_as(&original));
146    /// ```
147    ///
148    /// See also [`UnchangedOr`].
149    #[inline]
150    pub fn unchanged_or_same_as(&self, original: &T) -> bool {
151        if self.is_unchanged() {
152            return true;
153        }
154        let mut raw = TVMFFIAny::new();
155        // SAFETY: the borrowed cell is used only while original is alive.
156        unsafe {
157            T::container_copy_to_any_view(original, &mut raw);
158        }
159        raw_ffi_any_same_as(raw, *self.data.as_raw_ffi_any())
160    }
161
162    /// Move out the replacement.
163    ///
164    /// # Returns
165    ///
166    /// The replacement, or `None` when the result is unchanged.
167    #[inline]
168    pub fn into_option(self) -> Option<T> {
169        if self.is_unchanged() {
170            return None;
171        }
172        // SAFETY: constructors and conversions maintain the declared T.
173        unsafe {
174            let mut raw = Any::into_raw_ffi_any(self.data);
175            Some(T::container_move_from_any_after_check(&mut raw))
176        }
177    }
178
179    /// Move out the replacement, or `original` when the result is unchanged.
180    ///
181    /// `original` is the value the callback was given; to produce it only when
182    /// needed, use `into_option().unwrap_or_else(..)`.
183    ///
184    /// # Arguments
185    ///
186    /// * `original` - The original value, kept when the result is unchanged.
187    ///
188    /// # Returns
189    ///
190    /// The replacement, or `original`.
191    #[inline]
192    pub fn value_or_unchanged(self, original: T) -> T {
193        self.into_option().unwrap_or(original)
194    }
195
196    /// Convert only the replacement, preserving an unchanged result.
197    ///
198    /// # Arguments
199    ///
200    /// * `convert` - Converts the replacement; called only when there is one.
201    ///
202    /// # Returns
203    ///
204    /// The converted result.
205    #[inline]
206    pub fn map<U: ContainerElement>(self, convert: impl FnOnce(T) -> U) -> UnchangedOr<U> {
207        match self.into_option() {
208            Some(value) => UnchangedOr::changed(convert(value)),
209            None => UnchangedOr::unchanged(),
210        }
211    }
212}
213
214impl UnchangedOr<Any> {
215    /// Wrap a successful erased carrier, which may hold the unchanged marker.
216    #[inline(always)]
217    pub(crate) fn from_any(data: Any) -> Self {
218        Self {
219            data,
220            _marker: PhantomData,
221        }
222    }
223
224    #[inline(always)]
225    pub(crate) fn from_carrier(data: Any) -> Result<Self> {
226        if data.type_index() == TVMFFITypeIndex::kTVMFFIError as i32 {
227            core::hint::cold_path();
228            // Transfer ownership directly into the checked cold conversion.
229            return unsafe {
230                let raw = Any::into_raw_ffi_any(data);
231                Err(structural_error_from_raw(raw))
232            };
233        }
234        Ok(Self {
235            data,
236            _marker: PhantomData,
237        })
238    }
239}
240
241impl<T: ContainerElement> Clone for UnchangedOr<T> {
242    #[inline]
243    fn clone(&self) -> Self {
244        Self {
245            data: self.data.clone(),
246            _marker: PhantomData,
247        }
248    }
249}
250
251crate::impl_into_arg!(impl[T: ContainerElement] UnchangedOr<T>);
252
253impl<'b, T: ContainerElement> TryFrom<&'b Any> for UnchangedOr<T> {
254    type Error = Error;
255    #[inline]
256    fn try_from(value: &'b Any) -> Result<Self> {
257        TryFromTemp::<Self>::try_from(value).map(TryFromTemp::into_value)
258    }
259}
260
261impl<T: ContainerElement> TryFrom<Any> for UnchangedOr<T> {
262    type Error = Error;
263    #[inline]
264    fn try_from(value: Any) -> Result<Self> {
265        TryFromTemp::<Self>::try_from(value).map(TryFromTemp::into_value)
266    }
267}
268
269impl<'a, T: ContainerElement> TryFrom<AnyView<'a>> for UnchangedOr<T> {
270    type Error = Error;
271    #[inline]
272    fn try_from(value: AnyView<'a>) -> Result<Self> {
273        TryFromTemp::<Self>::try_from(value).map(TryFromTemp::into_value)
274    }
275}
276
277#[inline]
278pub(crate) fn is_unchanged(value: &Any) -> bool {
279    value.type_index() == TVMFFITypeIndex::kTVMFFIUnchanged as i32
280}
281
282// -----------------------------------------------------------------------------
283// AnyCompatible: low-level FFI carrier conversions.
284// -----------------------------------------------------------------------------
285
286// SAFETY: the unchanged ABI tag has no payload or owned resources.
287unsafe impl AnyCompatible for Unchanged {
288    unsafe fn copy_to_any_view(_src: &Self, data: &mut TVMFFIAny) {
289        *data = TVMFFIAny::new();
290        data.type_index = TVMFFITypeIndex::kTVMFFIUnchanged as i32;
291    }
292
293    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
294        unsafe { Self::copy_to_any_view(&src, data) };
295    }
296
297    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
298        data.type_index == TVMFFITypeIndex::kTVMFFIUnchanged as i32
299    }
300
301    unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {
302        Self
303    }
304
305    unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {
306        Self
307    }
308
309    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> std::result::Result<Self, ()> {
310        unsafe { Self::check_any_strict(data).then_some(Self).ok_or(()) }
311    }
312
313    fn type_str() -> std::string::String {
314        "Unchanged".into()
315    }
316
317    fn type_schema() -> std::string::String {
318        crate::type_traits::type_schema("ffi.Unchanged", &[])
319    }
320}
321
322crate::impl_try_from_any!(Unchanged);
323crate::impl_into_arg!(Unchanged);
324
325// SAFETY: the carrier contains either the resource-free marker or exactly
326// T's owning representation. Borrowing never acquires ownership; moving
327// transfers the carrier once. Non-strict conversions materialize a valid T.
328unsafe impl<T: ContainerElement> AnyCompatible for UnchangedOr<T> {
329    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
330        *data = *src.data.as_raw_ffi_any();
331    }
332
333    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
334        *data = Any::into_raw_ffi_any(src.data);
335    }
336
337    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
338        if T::CONTAINER_IS_ANY {
339            // An erased successful result excludes the ABI's error channel.
340            data.type_index != TVMFFITypeIndex::kTVMFFIError as i32
341        } else {
342            unsafe { Unchanged::check_any_strict(data) || T::container_check_any_strict(data) }
343        }
344    }
345
346    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
347        unsafe { Unchanged::check_any_strict(data) || T::container_match_constraints(data) }
348    }
349
350    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
351        if unsafe { Unchanged::check_any_strict(data) } {
352            return Self::unchanged();
353        }
354        // Materialize T, including numeric narrowing, before storing its value.
355        unsafe { Self::changed(T::container_copy_from_any_view_after_check(data)) }
356    }
357
358    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
359        unsafe {
360            Self {
361                data: Any::from_raw_ffi_any(std::mem::replace(data, TVMFFIAny::new())),
362                _marker: PhantomData,
363            }
364        }
365    }
366
367    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> std::result::Result<Self, ()> {
368        if T::CONTAINER_IS_ANY && data.type_index == TVMFFITypeIndex::kTVMFFIError as i32 {
369            return Err(());
370        }
371        if unsafe { Unchanged::check_any_strict(data) } {
372            return Ok(Self::unchanged());
373        }
374        unsafe { T::container_try_cast_from_any_view(data).map(Self::changed) }
375    }
376
377    fn type_str() -> std::string::String {
378        format!("UnchangedOr<{}>", T::container_type_str())
379    }
380
381    fn type_schema() -> std::string::String {
382        crate::type_traits::type_schema("UnchangedOr", &[T::container_type_schema()])
383    }
384}
385
386// -----------------------------------------------------------------------------
387// Conversions into an erased mutation result.
388// -----------------------------------------------------------------------------
389
390/// `Unchanged.into()` keeps the original value.
391impl From<Unchanged> for UnchangedOr<Any> {
392    #[inline]
393    fn from(_: Unchanged) -> Self {
394        Self::unchanged()
395    }
396}
397
398/// A managed reference replaces the original value.
399impl<T: crate::object::ObjectRefCore> From<T> for UnchangedOr<Any> {
400    #[inline]
401    fn from(value: T) -> Self {
402        Self::changed(Any::from(value))
403    }
404}
405
406/// A typed result keeps its unchanged marker or replacement.
407impl<T: crate::object::ObjectRefCore> From<UnchangedOr<T>> for UnchangedOr<Any> {
408    #[inline]
409    fn from(value: UnchangedOr<T>) -> Self {
410        Self::from_any(Any::from(value))
411    }
412}
413
414macro_rules! impl_unchanged_or_any_from_scalar {
415    ($($ty:ty),*) => {
416        $(
417            /// A scalar replaces the original value.
418            impl From<$ty> for UnchangedOr<Any> {
419                #[inline]
420                fn from(value: $ty) -> Self {
421                    Self::changed(Any::from(value))
422                }
423            }
424
425            /// A typed scalar result keeps its unchanged marker or replacement.
426            impl From<UnchangedOr<$ty>> for UnchangedOr<Any> {
427                #[inline]
428                fn from(value: UnchangedOr<$ty>) -> Self {
429                    Self::from_any(Any::from(value))
430                }
431            }
432        )*
433    };
434}
435impl_unchanged_or_any_from_scalar!(
436    bool, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64
437);