tvm_ffi/any.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//! [`Any`] and [`AnyView`]: owned and borrowed type-erased FFI values.
20
21use crate::error::Error;
22use crate::object;
23use crate::type_traits::AnyCompatible;
24use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
25use tvm_ffi_sys::{TVMFFIAny, TVMFFIAnyViewToOwnedAny};
26
27/// A borrowed, type-erased FFI value.
28///
29/// `AnyView` holds any FFI value, such as an integer, a string or an object,
30/// without owning it: it does not retain objects, and its lifetime `'a` keeps
31/// it from outliving the value it borrows. It is `Copy` and is the argument
32/// type of FFI calls. Convert it into an [`Any`] to own the value.
33///
34/// # Examples
35///
36/// ```
37/// use tvm_ffi::{Any, AnyView, Array};
38///
39/// let array = Array::from_vec(vec![1_i64, 2, 3]);
40/// let view = AnyView::from(&array);
41/// assert_eq!(view.downcast_ref::<Array<i64>>().unwrap().len(), 3);
42///
43/// let owned = Any::from(view);
44/// assert_eq!(Array::<i64>::try_from(owned)?.len(), 3);
45/// # Ok::<(), tvm_ffi::Error>(())
46/// ```
47#[derive(Copy, Clone)]
48#[repr(C)]
49pub struct AnyView<'a> {
50 data: TVMFFIAny,
51 /// needs to explicit mark lifetime to avoid lifetime mismatch
52 _phantom: std::marker::PhantomData<&'a ()>,
53}
54
55/// An owned, type-erased FFI value.
56///
57/// `Any` holds any FFI value, such as an integer, a string or an object, and
58/// owns it: cloning an `Any` that holds an object retains the object, and
59/// dropping it releases the object. Any [`AnyCompatible`] value converts into
60/// it with `From`; `TryFrom` (converting), [`downcast_ref`](Self::downcast_ref)
61/// (borrowing) and [`match_any!`](crate::match_any) read it back. Borrow it as an [`AnyView`] to pass it without retaining.
62///
63/// The one value it does not own is a `DLTensor*` converted from an
64/// [`AnyView`], as in C++: that `Any` borrows the tensor and must not outlive
65/// it.
66///
67/// # Examples
68///
69/// ```
70/// use tvm_ffi::Any;
71///
72/// let value = Any::from(42_i64);
73/// assert_eq!(i64::try_from(&value)?, 42);
74/// assert!(tvm_ffi::String::try_from(&value).is_err());
75///
76/// let text = Any::from(tvm_ffi::String::from("hello"));
77/// assert_eq!(text.downcast_ref::<tvm_ffi::String>().unwrap().as_str(), "hello");
78/// # Ok::<(), tvm_ffi::Error>(())
79/// ```
80#[repr(C)]
81pub struct Any {
82 data: TVMFFIAny,
83}
84
85//---------------------
86// AnyView
87//---------------------
88impl<'a> AnyView<'a> {
89 /// Create a view of `None`, the empty FFI value.
90 ///
91 /// # Returns
92 ///
93 /// A view holding `None`.
94 pub fn new() -> Self {
95 Self {
96 data: TVMFFIAny::new(),
97 _phantom: std::marker::PhantomData,
98 }
99 }
100
101 /// Borrow a live managed object without acquiring ownership.
102 #[doc(hidden)]
103 #[inline(always)]
104 pub fn from_object<T: object::ObjectCore>(value: &'a T) -> Self {
105 let pointer = std::ptr::from_ref(value).cast::<tvm_ffi_sys::TVMFFIObject>();
106 // ObjectCore guarantees the prefix and stable managed allocation. A
107 // builder or a moved-out destructor value is not a live managed object.
108 let header = unsafe { &*pointer };
109 assert!(
110 header.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32
111 && header.deleter.is_some()
112 && header
113 .combined_ref_count
114 .load(std::sync::atomic::Ordering::Relaxed)
115 & tvm_ffi_sys::COMBINED_REF_COUNT_MASK_U32
116 != 0,
117 "cannot borrow an unmanaged or dead object as AnyView"
118 );
119 let mut data = TVMFFIAny::new();
120 data.type_index = header.type_index;
121 data.data_union.v_obj = pointer.cast_mut();
122 // The source borrow bounds the view; the dynamic type comes from the
123 // allocation even when value borrows a base-class prefix.
124 unsafe { Self::from_raw_ffi_any(data) }
125 }
126
127 /// Return the runtime type index of the viewed value.
128 ///
129 /// Indices below `TypeIndex::kTVMFFIStaticObjectBegin` are the built-in
130 /// non-object types; the others are object types.
131 ///
132 /// # Returns
133 ///
134 /// The type index.
135 #[inline(always)]
136 pub fn type_index(&self) -> i32 {
137 self.data.type_index
138 }
139
140 /// The registered type key of the viewed value, such as `"int"` or
141 /// `"ffi.Array"`. See also [`Any::type_key`].
142 #[inline]
143 pub fn type_key(&self) -> &'static str {
144 object::registered_type_key(self.data.type_index)
145 }
146
147 /// Whether the value is None.
148 #[inline(always)]
149 pub fn is_none(&self) -> bool {
150 self.data.type_index == TypeIndex::kTVMFFINone as i32
151 }
152
153 /// Borrow the raw ABI representation.
154 /// Copying it does not retain referenced data or extend its lifetime.
155 #[inline(always)]
156 pub fn as_raw_ffi_any(&self) -> &TVMFFIAny {
157 &self.data
158 }
159
160 /// Construct a borrowed view from its ABI representation.
161 ///
162 /// # Safety
163 ///
164 /// `data.type_index` must describe the payload, and the caller must keep
165 /// every resource it references alive for the view's complete lifetime.
166 ///
167 /// `kTVMFFIObjectRValueRef` carries a further obligation: `v_ptr` must
168 /// point to a writable slot the caller uniquely owns, holding one strong
169 /// reference. Owning the view takes that reference and writes null back
170 /// through the pointer, so the view must be converted at most once and no
171 /// other access to the slot may overlap the conversion.
172 #[inline(always)]
173 pub unsafe fn from_raw_ffi_any(data: TVMFFIAny) -> Self {
174 Self {
175 data,
176 _phantom: std::marker::PhantomData,
177 }
178 }
179
180 /// Borrow the viewed value as `T` when it holds one, without copying it.
181 ///
182 /// `T` is an object type such as `ArrayObj`, a managed reference such as
183 /// `Array<i64>`, or a value stored in place such as `String` or `i64`. The
184 /// check is strict and never converts, unlike `TryFrom`.
185 /// The borrow does not change any reference count and is tied to this view,
186 /// which holds its own copy of the value's cell.
187 ///
188 /// # Returns
189 ///
190 /// The borrowed value, or `None`.
191 ///
192 /// See also [`Any::downcast_ref`].
193 #[inline(always)]
194 pub fn downcast_ref<T: crate::type_traits::DowncastRefFromAny>(&self) -> Option<&T> {
195 // SAFETY: the view holds a valid cell for as long as it is borrowed.
196 unsafe { T::downcast_ref_from_any(&self.data) }
197 }
198
199 /// Whether the viewed value is a `T` as is, by the strict check of
200 /// [`downcast_ref`](Self::downcast_ref), without conversion.
201 /// See also [`Any::is`].
202 #[inline(always)]
203 pub fn is<T: AnyCompatible>(&self) -> bool {
204 // SAFETY: the view holds a valid cell.
205 unsafe { T::check_any_strict(&self.data) }
206 }
207
208 /// The strong reference count of the held object, for tests and debugging;
209 /// `None` if the value is not an object.
210 #[doc(hidden)]
211 pub fn debug_strong_count(&self) -> Option<usize> {
212 unsafe {
213 if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
214 Some(object::unsafe_::strong_count(self.data.data_union.v_obj))
215 } else {
216 None
217 }
218 }
219 }
220}
221
222impl<'a> From<&'a object::Object> for AnyView<'a> {
223 #[inline(always)]
224 fn from(value: &'a object::Object) -> Self {
225 Self::from_object(value)
226 }
227}
228
229impl<'a, T: AnyCompatible> From<&'a T> for AnyView<'a> {
230 #[inline(always)]
231 fn from(value: &'a T) -> Self {
232 unsafe {
233 let mut data = TVMFFIAny::new();
234 T::copy_to_any_view(value, &mut data);
235 Self {
236 data,
237 _phantom: std::marker::PhantomData,
238 }
239 }
240 }
241}
242
243impl<'a> From<&AnyView<'a>> for AnyView<'a> {
244 #[inline(always)]
245 fn from(value: &AnyView<'a>) -> Self {
246 *value
247 }
248}
249
250impl Default for AnyView<'_> {
251 fn default() -> Self {
252 Self::new()
253 }
254}
255
256/// Holder for Any value
257///
258/// This is used to define try_from rule while conforming to orphan rule
259/// Users should not use this directly
260#[doc(hidden)]
261pub struct TryFromTemp<T> {
262 value: T,
263}
264
265impl<T> TryFromTemp<T> {
266 /// Create a new holder for the value
267 #[inline(always)]
268 pub fn new(value: T) -> Self {
269 Self { value }
270 }
271
272 /// Move the value out of the holder
273 #[inline(always)]
274 pub fn into_value(this: Self) -> T {
275 this.value
276 }
277}
278
279//---------------------
280// Any
281//---------------------
282impl Any {
283 /// Create an `Any` holding `None`, the empty FFI value.
284 ///
285 /// # Returns
286 ///
287 /// An `Any` holding `None`.
288 #[inline(always)]
289 pub fn new() -> Self {
290 Self {
291 data: TVMFFIAny::new(),
292 }
293 }
294
295 /// Return the runtime type index of the stored value.
296 ///
297 /// Indices below `TypeIndex::kTVMFFIStaticObjectBegin` are the built-in
298 /// non-object types; the others are object types.
299 ///
300 /// # Returns
301 ///
302 /// The type index.
303 #[inline(always)]
304 pub fn type_index(&self) -> i32 {
305 self.data.type_index
306 }
307
308 /// The registered type key of the stored value, such as `"int"` or
309 /// `"ffi.Array"`, as C++ `Any::GetTypeKey`.
310 ///
311 /// ```
312 /// use tvm_ffi::{Any, Array};
313 /// assert_eq!(Any::from(1_i64).type_key(), "int");
314 /// assert_eq!(Any::from(Array::from_vec(vec![1_i64])).type_key(), "ffi.Array");
315 /// ```
316 #[inline]
317 pub fn type_key(&self) -> &'static str {
318 object::registered_type_key(self.data.type_index)
319 }
320
321 /// Whether the value is None.
322 #[inline(always)]
323 pub fn is_none(&self) -> bool {
324 self.data.type_index == TypeIndex::kTVMFFINone as i32
325 }
326
327 /// Borrow the raw ABI representation, which this value owns.
328 /// Copying it does not retain referenced data or extend its lifetime.
329 #[inline(always)]
330 pub fn as_raw_ffi_any(&self) -> &TVMFFIAny {
331 &self.data
332 }
333 /// Borrow the stored value as `T` when it holds one, without copying it.
334 ///
335 /// `T` is an object type such as `ArrayObj`, a managed reference such as
336 /// `Array<i64>`, or a value stored in place such as `String` or `i64`. The
337 /// check is strict and never converts, unlike `TryFrom`.
338 /// This neither consumes `self` nor changes any reference count, and the
339 /// returned reference cannot outlive `self`.
340 ///
341 /// # Returns
342 ///
343 /// The borrowed object, or `None`.
344 ///
345 /// ```
346 /// use tvm_ffi::{collections::array::ArrayObj, Any, Array};
347 /// let value = Any::from(Array::from_vec(vec![1_i64, 2]));
348 /// assert_eq!(value.downcast_ref::<ArrayObj>().unwrap().size, 2);
349 /// assert_eq!(value.downcast_ref::<Array<i64>>().unwrap()[1], 2);
350 /// assert!(value.downcast_ref::<i64>().is_none());
351 /// ```
352 ///
353 /// See also [`match_any!`](crate::match_any).
354 #[inline]
355 pub fn downcast_ref<T: crate::type_traits::DowncastRefFromAny>(&self) -> Option<&T> {
356 // SAFETY: the owned cell stays valid for as long as `self` is borrowed.
357 unsafe { T::downcast_ref_from_any(&self.data) }
358 }
359
360 /// Whether the stored value is a `T` as is, by the strict check of
361 /// [`downcast_ref`](Self::downcast_ref), without conversion, as std
362 /// `Any::is`. It covers every [`AnyCompatible`] type, such as `bool`.
363 ///
364 /// ```
365 /// use tvm_ffi::{Any, Array};
366 /// let value = Any::from(Array::from_vec(vec![1_i64, 2]));
367 /// assert!(value.is::<Array<i64>>());
368 /// assert!(!value.is::<Array<f64>>());
369 /// assert!(Any::from(true).is::<bool>());
370 /// assert!(!Any::from(1_i64).is::<f64>());
371 /// ```
372 #[inline(always)]
373 pub fn is<T: AnyCompatible>(&self) -> bool {
374 // SAFETY: the owned cell is valid.
375 unsafe { T::check_any_strict(&self.data) }
376 }
377
378 /// Return a pointer to the raw ABI representation, for a runtime call that
379 /// writes an owned result into it as an out-parameter.
380 ///
381 /// Writing through the pointer is unsafe: the cell must afterwards hold a
382 /// value this `Any` may own and release, and the previous value must have
383 /// been released or moved out.
384 #[inline(always)]
385 pub fn as_raw_ffi_any_mut(&mut self) -> *mut TVMFFIAny {
386 &mut self.data
387 }
388
389 /// Give up ownership of the value as its raw ABI representation, as
390 /// `Box::into_raw` does. Rebuild it with [`from_raw_ffi_any`](Self::from_raw_ffi_any)
391 /// to release it.
392 #[inline(always)]
393 pub fn into_raw_ffi_any(self) -> TVMFFIAny {
394 let this = std::mem::ManuallyDrop::new(self);
395 this.data
396 }
397
398 /// Take ownership of a raw ABI representation.
399 ///
400 /// # Safety
401 ///
402 /// `data.type_index` must describe the payload, and the caller must hand
403 /// over the ownership `data` carries, such as one strong reference for an
404 /// object, so it is released exactly once, by this `Any`.
405 #[inline(always)]
406 pub unsafe fn from_raw_ffi_any(data: TVMFFIAny) -> Self {
407 Self { data }
408 }
409
410 /// The strong reference count of the held object, for tests and debugging;
411 /// `None` if the value is not an object.
412 #[doc(hidden)]
413 pub fn debug_strong_count(&self) -> Option<usize> {
414 unsafe {
415 if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
416 Some(object::unsafe_::strong_count(self.data.data_union.v_obj))
417 } else {
418 None
419 }
420 }
421 }
422}
423
424impl Default for Any {
425 #[inline(always)]
426 fn default() -> Self {
427 Self::new()
428 }
429}
430
431impl Clone for Any {
432 #[inline]
433 fn clone(&self) -> Self {
434 if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
435 unsafe { object::unsafe_::inc_ref(self.data.data_union.v_obj) }
436 }
437 Self { data: self.data }
438 }
439}
440
441impl Drop for Any {
442 #[inline(always)]
443 fn drop(&mut self) {
444 if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
445 unsafe { object::unsafe_::dec_ref(self.data.data_union.v_obj) }
446 }
447 }
448}
449
450// convert Any ref to AnyView
451impl<'a> From<&'a Any> for AnyView<'a> {
452 #[inline(always)]
453 fn from(value: &'a Any) -> Self {
454 Self {
455 data: value.data,
456 _phantom: std::marker::PhantomData,
457 }
458 }
459}
460
461/// Formats the value as its `repr`, the text the runtime printer gives in
462/// every language, such as `(1, 2)` for an array or `"hi"` for a string.
463/// Object references format the same way.
464///
465/// # Examples
466///
467/// ```
468/// use tvm_ffi::{AnyView, Array};
469///
470/// let xs = Array::from_vec(vec![1_i64, 2]);
471/// assert_eq!(AnyView::from(&xs).to_string(), "(1, 2)");
472/// assert_eq!(xs.to_string(), "(1, 2)");
473/// ```
474impl std::fmt::Display for AnyView<'_> {
475 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476 let repr = crate::cached_global_func!("ffi.ReprPrint")
477 .call_packed(&[*self])
478 .and_then(crate::String::try_from);
479 match repr {
480 Ok(text) => f.pad(text.as_str()),
481 // Formatting cannot fail, so a printer error falls back to the type key.
482 Err(_) => f.pad(&object::type_key_of_index(self.type_index())),
483 }
484 }
485}
486
487/// Formats the value as its `repr`; see [`AnyView`].
488impl std::fmt::Display for Any {
489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 std::fmt::Display::fmt(&AnyView::from(self), f)
491 }
492}
493
494/// Formats the type key and the `repr`, such as `AnyView(int: 1)`.
495impl std::fmt::Debug for AnyView<'_> {
496 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497 let key = object::type_key_of_index(self.type_index());
498 write!(f, "AnyView({key}: {self})")
499 }
500}
501
502/// Formats the type key and the `repr`, such as `Any(int: 1)`.
503impl std::fmt::Debug for Any {
504 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
505 let view = AnyView::from(self);
506 let key = object::type_key_of_index(view.type_index());
507 write!(f, "Any({key}: {view})")
508 }
509}
510
511/// Whether a `TVMFFIAny` cell owns everything it holds, so its owning form is a
512/// bitwise copy.
513#[inline]
514pub(crate) fn is_plain_inline(type_index: i32) -> bool {
515 type_index < TypeIndex::kTVMFFIRawStr as i32
516 || type_index == TypeIndex::kTVMFFISmallStr as i32
517 || type_index == TypeIndex::kTVMFFISmallBytes as i32
518 || type_index == TypeIndex::kTVMFFIUnchanged as i32
519}
520
521/// Takes ownership of the viewed value: objects gain a reference, borrowed
522/// strings and bytes are copied, and an [`RValueRef`](crate::rvalue_ref::RValueRef)
523/// gives up its object.
524///
525/// A `DLTensor*` has no reference count to take, so it is kept as is, as in
526/// C++: the `Any` borrows the tensor and must not outlive it. Convert it to a
527/// [`Tensor`](crate::Tensor) to own the tensor.
528///
529/// # Panics
530///
531/// Panics if the view holds an `RValueRef` whose object an earlier conversion
532/// already took.
533impl From<AnyView<'_>> for Any {
534 #[inline]
535 fn from(value: AnyView<'_>) -> Self {
536 let data = value.data;
537 // Owning a borrowed object is the same incref `Any::clone` does below.
538 if data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
539 unsafe { object::unsafe_::inc_ref(data.data_union.v_obj) };
540 return Self { data };
541 }
542 if is_plain_inline(data.type_index) {
543 return Self { data };
544 }
545 // What is left borrows foreign storage and needs the runtime.
546 any_view_to_owned_via_runtime(data)
547 }
548}
549
550/// Out of line so the inlined conversions above stay leaf code, without the
551/// stack frame and unwind path this call needs.
552#[cold]
553#[inline(never)]
554fn any_view_to_owned_via_runtime(view: TVMFFIAny) -> Any {
555 unsafe {
556 let mut data = TVMFFIAny::new();
557 crate::check_safe_call!(TVMFFIAnyViewToOwnedAny(&view, &mut data)).unwrap();
558 Any { data }
559 }
560}
561
562impl<T: AnyCompatible> From<T> for Any {
563 #[inline(always)]
564 fn from(value: T) -> Self {
565 unsafe {
566 let mut data = TVMFFIAny::new();
567 T::move_to_any(value, &mut data);
568 Self { data }
569 }
570 }
571}
572
573impl<'a, T: AnyCompatible> TryFrom<AnyView<'a>> for TryFromTemp<T> {
574 type Error = crate::error::Error;
575 #[inline]
576 fn try_from(value: AnyView<'a>) -> Result<Self, Self::Error> {
577 unsafe {
578 if T::check_any_strict(&value.data) {
579 Ok(TryFromTemp::new(T::copy_from_any_view_after_check(
580 &value.data,
581 )))
582 } else {
583 T::try_cast_from_any_view(&value.data)
584 .map_err(|_| {
585 let msg = format!(
586 "Cannot convert from type `{}` to `{}`",
587 T::get_mismatch_type_info(&value.data),
588 T::type_str()
589 );
590 crate::error::Error::new(crate::error::TYPE_ERROR, &msg)
591 })
592 .map(TryFromTemp::new)
593 }
594 }
595 }
596}
597
598impl<'a, T: AnyCompatible> TryFrom<&'a Any> for TryFromTemp<T> {
599 type Error = crate::error::Error;
600 #[inline]
601 fn try_from(value: &'a Any) -> Result<Self, Self::Error> {
602 TryFromTemp::try_from(AnyView::from(value))
603 }
604}
605
606impl<T: AnyCompatible> TryFrom<Any> for TryFromTemp<T> {
607 type Error = crate::error::Error;
608 #[inline]
609 fn try_from(value: Any) -> Result<Self, Self::Error> {
610 unsafe {
611 if T::check_any_strict(&value.data) {
612 let mut value = std::mem::ManuallyDrop::new(value);
613 Ok(TryFromTemp::new(T::move_from_any_after_check(
614 &mut value.data,
615 )))
616 } else {
617 T::try_cast_from_any_view(&value.data)
618 .map_err(|_| {
619 let msg = format!(
620 "Cannot convert from type `{}` to `{}`",
621 T::get_mismatch_type_info(&value.data),
622 T::type_str()
623 );
624 crate::error::Error::new(crate::error::TYPE_ERROR, &msg)
625 })
626 .map(TryFromTemp::new)
627 }
628 }
629 }
630}
631
632crate::impl_any_compatible_conversions!(
633 (),
634 bool,
635 i8,
636 i16,
637 i32,
638 i64,
639 isize,
640 u8,
641 u16,
642 u32,
643 u64,
644 usize,
645 f32,
646 f64,
647 crate::string::String,
648 crate::string::Bytes,
649 crate::big_int::BigInt,
650 tvm_ffi_sys::dlpack::DLDataType,
651 tvm_ffi_sys::dlpack::DLDevice,
652);
653// Only out of `Any`: a raw pointer and the root reference are not call arguments.
654crate::impl_try_from_any!(*mut core::ffi::c_void, crate::object::ObjectRef);
655crate::impl_into_arg!(Any, *mut core::ffi::c_void, crate::object::ObjectRef);
656
657crate::impl_try_from_any_for_parametric!(Option<T>);
658crate::impl_into_arg!(impl[T: AnyCompatible + Clone] Option<T>);
659
660/// The conversion of a typed function argument, whose error names the
661/// argument's index.
662pub(crate) trait ArgTryFromAnyView: Sized + crate::type_traits::TypeSchema {
663 fn try_from_any_view(value: &AnyView, arg_index: usize) -> Result<Self, Error>;
664}
665
666impl<T: AnyCompatible> ArgTryFromAnyView for T {
667 fn try_from_any_view(value: &AnyView, arg_index: usize) -> Result<Self, Error> {
668 unsafe {
669 if T::check_any_strict(&value.data) {
670 Ok(T::copy_from_any_view_after_check(&value.data))
671 } else {
672 T::try_cast_from_any_view(&value.data).map_err(|_| {
673 let msg = format!(
674 "Argument #{}: Cannot convert from type `{}` to `{}`",
675 arg_index,
676 T::get_mismatch_type_info(&value.data),
677 T::type_str()
678 );
679 crate::error::Error::new(crate::error::TYPE_ERROR, &msg)
680 })
681 }
682 }
683 }
684}