tvm-ffi 0.1.16

tvm-ffi rust support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//! Typed unchanged-or-replacement results for structural mutation.

use std::marker::PhantomData;

use super::structural_common::{raw_ffi_any_same_as, structural_error_from_raw};

use crate::any::{Any, AnyView, TryFromTemp};
use crate::error::{Error, Result};
use crate::tvm_ffi_sys::{TVMFFIAny, TVMFFITypeIndex};
use crate::type_traits::{AnyCompatible, ContainerElement};

/// A marker result that keeps the original value.
///
/// A map or mutation callback returns `Unchanged`, usually as
/// `Unchanged.into()`, to keep the value it was given without retaining or
/// cloning it. A pre-order map still descends into the original value's
/// children.
///
/// # Examples
///
/// ```
/// use tvm_ffi::{Any, Unchanged, UnchangedOr};
///
/// let result: UnchangedOr<Any> = Unchanged.into();
/// assert!(result.is_unchanged());
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Unchanged;

/// Either a replacement value of type `T`, or [`Unchanged`] to keep the
/// original.
///
/// Structural map and mutation callbacks return `Result<UnchangedOr<Any>>`.
/// It is like `Option<T>` whose `None` means "keep what was there", stored in
/// one FFI value. `UnchangedOr<Any>` converts with `.into()` from
/// [`Unchanged`], from a managed reference or scalar, and from a typed
/// `UnchangedOr<T>`. `T` is an FFI value type or [`Any`]. Converting the
/// wrapper into `Any` keeps the marker; use [`value_or_unchanged`](Self::value_or_unchanged) or
/// [`into_option`](Self::into_option) when an actual value is needed.
///
/// # Examples
///
/// ```
/// use tvm_ffi::UnchangedOr;
///
/// fn double_even(value: i64) -> UnchangedOr<i64> {
///     if value % 2 == 0 {
///         UnchangedOr::changed(value * 2)
///     } else {
///         UnchangedOr::unchanged()
///     }
/// }
///
/// assert_eq!(double_even(4).value_or_unchanged(4), 8);
/// assert_eq!(double_even(3).value_or_unchanged(3), 3);
/// ```
#[repr(transparent)]
pub struct UnchangedOr<T: ContainerElement = Any> {
    data: Any,
    _marker: PhantomData<T>,
}

impl<T: ContainerElement> UnchangedOr<T> {
    /// Create a result that keeps the original value, without borrowing or cloning
    /// it.
    ///
    /// # Returns
    ///
    /// An unchanged result.
    #[inline]
    pub fn unchanged() -> Self {
        Self {
            data: Unchanged.into(),
            _marker: PhantomData,
        }
    }

    /// Create a result that replaces the original value.
    ///
    /// # Arguments
    ///
    /// * `value` - The replacement.
    ///
    /// # Returns
    ///
    /// A result holding `value`.
    #[inline]
    pub fn changed(value: T) -> Self {
        let mut raw = TVMFFIAny::new();
        // SAFETY: ContainerElement transfers exactly one owning value.
        unsafe {
            T::container_move_to_any(value, &mut raw);
            Self {
                data: Any::from_raw_ffi_any(raw),
                _marker: PhantomData,
            }
        }
    }

    /// Return whether this result keeps the original value.
    ///
    /// # Returns
    ///
    /// `true` if the result is unchanged.
    #[inline]
    pub fn is_unchanged(&self) -> bool {
        is_unchanged(&self.data)
    }

    /// Return whether this result is unchanged or holds `original` itself.
    ///
    /// An object counts as the same only when it is the same object, not an equal
    /// copy. Use it to tell whether anything was rewritten.
    ///
    /// # Arguments
    ///
    /// * `original` - The original value.
    ///
    /// # Returns
    ///
    /// `true` if the result is unchanged or holds `original`.
    ///
    /// ```
    /// use tvm_ffi::{Array, UnchangedOr};
    /// let original = Array::from_vec(vec![1_i64]);
    /// assert!(UnchangedOr::changed(original.clone()).unchanged_or_same_as(&original));
    /// ```
    ///
    /// See also [`UnchangedOr`].
    #[inline]
    pub fn unchanged_or_same_as(&self, original: &T) -> bool {
        if self.is_unchanged() {
            return true;
        }
        let mut raw = TVMFFIAny::new();
        // SAFETY: the borrowed cell is used only while original is alive.
        unsafe {
            T::container_copy_to_any_view(original, &mut raw);
        }
        raw_ffi_any_same_as(raw, *self.data.as_raw_ffi_any())
    }

    /// Move out the replacement.
    ///
    /// # Returns
    ///
    /// The replacement, or `None` when the result is unchanged.
    #[inline]
    pub fn into_option(self) -> Option<T> {
        if self.is_unchanged() {
            return None;
        }
        // SAFETY: constructors and conversions maintain the declared T.
        unsafe {
            let mut raw = Any::into_raw_ffi_any(self.data);
            Some(T::container_move_from_any_after_check(&mut raw))
        }
    }

    /// Move out the replacement, or `original` when the result is unchanged.
    ///
    /// `original` is the value the callback was given; to produce it only when
    /// needed, use `into_option().unwrap_or_else(..)`.
    ///
    /// # Arguments
    ///
    /// * `original` - The original value, kept when the result is unchanged.
    ///
    /// # Returns
    ///
    /// The replacement, or `original`.
    #[inline]
    pub fn value_or_unchanged(self, original: T) -> T {
        self.into_option().unwrap_or(original)
    }

    /// Convert only the replacement, preserving an unchanged result.
    ///
    /// # Arguments
    ///
    /// * `convert` - Converts the replacement; called only when there is one.
    ///
    /// # Returns
    ///
    /// The converted result.
    #[inline]
    pub fn map<U: ContainerElement>(self, convert: impl FnOnce(T) -> U) -> UnchangedOr<U> {
        match self.into_option() {
            Some(value) => UnchangedOr::changed(convert(value)),
            None => UnchangedOr::unchanged(),
        }
    }
}

impl UnchangedOr<Any> {
    /// Wrap a successful erased carrier, which may hold the unchanged marker.
    #[inline(always)]
    pub(crate) fn from_any(data: Any) -> Self {
        Self {
            data,
            _marker: PhantomData,
        }
    }

    #[inline(always)]
    pub(crate) fn from_carrier(data: Any) -> Result<Self> {
        if data.type_index() == TVMFFITypeIndex::kTVMFFIError as i32 {
            core::hint::cold_path();
            // Transfer ownership directly into the checked cold conversion.
            return unsafe {
                let raw = Any::into_raw_ffi_any(data);
                Err(structural_error_from_raw(raw))
            };
        }
        Ok(Self {
            data,
            _marker: PhantomData,
        })
    }
}

impl<T: ContainerElement> Clone for UnchangedOr<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            _marker: PhantomData,
        }
    }
}

crate::impl_into_arg!(impl[T: ContainerElement] UnchangedOr<T>);

impl<'b, T: ContainerElement> TryFrom<&'b Any> for UnchangedOr<T> {
    type Error = Error;
    #[inline]
    fn try_from(value: &'b Any) -> Result<Self> {
        TryFromTemp::<Self>::try_from(value).map(TryFromTemp::into_value)
    }
}

impl<T: ContainerElement> TryFrom<Any> for UnchangedOr<T> {
    type Error = Error;
    #[inline]
    fn try_from(value: Any) -> Result<Self> {
        TryFromTemp::<Self>::try_from(value).map(TryFromTemp::into_value)
    }
}

impl<'a, T: ContainerElement> TryFrom<AnyView<'a>> for UnchangedOr<T> {
    type Error = Error;
    #[inline]
    fn try_from(value: AnyView<'a>) -> Result<Self> {
        TryFromTemp::<Self>::try_from(value).map(TryFromTemp::into_value)
    }
}

#[inline]
pub(crate) fn is_unchanged(value: &Any) -> bool {
    value.type_index() == TVMFFITypeIndex::kTVMFFIUnchanged as i32
}

// -----------------------------------------------------------------------------
// AnyCompatible: low-level FFI carrier conversions.
// -----------------------------------------------------------------------------

// SAFETY: the unchanged ABI tag has no payload or owned resources.
unsafe impl AnyCompatible for Unchanged {
    unsafe fn copy_to_any_view(_src: &Self, data: &mut TVMFFIAny) {
        *data = TVMFFIAny::new();
        data.type_index = TVMFFITypeIndex::kTVMFFIUnchanged as i32;
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        unsafe { Self::copy_to_any_view(&src, data) };
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        data.type_index == TVMFFITypeIndex::kTVMFFIUnchanged as i32
    }

    unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {
        Self
    }

    unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {
        Self
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> std::result::Result<Self, ()> {
        unsafe { Self::check_any_strict(data).then_some(Self).ok_or(()) }
    }

    fn type_str() -> std::string::String {
        "Unchanged".into()
    }

    fn type_schema() -> std::string::String {
        crate::type_traits::type_schema("ffi.Unchanged", &[])
    }
}

crate::impl_try_from_any!(Unchanged);
crate::impl_into_arg!(Unchanged);

// SAFETY: the carrier contains either the resource-free marker or exactly
// T's owning representation. Borrowing never acquires ownership; moving
// transfers the carrier once. Non-strict conversions materialize a valid T.
unsafe impl<T: ContainerElement> AnyCompatible for UnchangedOr<T> {
    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        *data = *src.data.as_raw_ffi_any();
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        *data = Any::into_raw_ffi_any(src.data);
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        if T::CONTAINER_IS_ANY {
            // An erased successful result excludes the ABI's error channel.
            data.type_index != TVMFFITypeIndex::kTVMFFIError as i32
        } else {
            unsafe { Unchanged::check_any_strict(data) || T::container_check_any_strict(data) }
        }
    }

    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
        unsafe { Unchanged::check_any_strict(data) || T::container_match_constraints(data) }
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        if unsafe { Unchanged::check_any_strict(data) } {
            return Self::unchanged();
        }
        // Materialize T, including numeric narrowing, before storing its value.
        unsafe { Self::changed(T::container_copy_from_any_view_after_check(data)) }
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        unsafe {
            Self {
                data: Any::from_raw_ffi_any(std::mem::replace(data, TVMFFIAny::new())),
                _marker: PhantomData,
            }
        }
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> std::result::Result<Self, ()> {
        if T::CONTAINER_IS_ANY && data.type_index == TVMFFITypeIndex::kTVMFFIError as i32 {
            return Err(());
        }
        if unsafe { Unchanged::check_any_strict(data) } {
            return Ok(Self::unchanged());
        }
        unsafe { T::container_try_cast_from_any_view(data).map(Self::changed) }
    }

    fn type_str() -> std::string::String {
        format!("UnchangedOr<{}>", T::container_type_str())
    }

    fn type_schema() -> std::string::String {
        crate::type_traits::type_schema("UnchangedOr", &[T::container_type_schema()])
    }
}

// -----------------------------------------------------------------------------
// Conversions into an erased mutation result.
// -----------------------------------------------------------------------------

/// `Unchanged.into()` keeps the original value.
impl From<Unchanged> for UnchangedOr<Any> {
    #[inline]
    fn from(_: Unchanged) -> Self {
        Self::unchanged()
    }
}

/// A managed reference replaces the original value.
impl<T: crate::object::ObjectRefCore> From<T> for UnchangedOr<Any> {
    #[inline]
    fn from(value: T) -> Self {
        Self::changed(Any::from(value))
    }
}

/// A typed result keeps its unchanged marker or replacement.
impl<T: crate::object::ObjectRefCore> From<UnchangedOr<T>> for UnchangedOr<Any> {
    #[inline]
    fn from(value: UnchangedOr<T>) -> Self {
        Self::from_any(Any::from(value))
    }
}

macro_rules! impl_unchanged_or_any_from_scalar {
    ($($ty:ty),*) => {
        $(
            /// A scalar replaces the original value.
            impl From<$ty> for UnchangedOr<Any> {
                #[inline]
                fn from(value: $ty) -> Self {
                    Self::changed(Any::from(value))
                }
            }

            /// A typed scalar result keeps its unchanged marker or replacement.
            impl From<UnchangedOr<$ty>> for UnchangedOr<Any> {
                #[inline]
                fn from(value: UnchangedOr<$ty>) -> Self {
                    Self::from_any(Any::from(value))
                }
            }
        )*
    };
}
impl_unchanged_or_any_from_scalar!(
    bool, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64
);