1use crate::any::{Any, AnyView};
20use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
21use tvm_ffi_sys::{TVMFFIAny, TVMFFIGetTypeInfo};
22
23pub unsafe trait AnyCompatible: Sized {
29 #[doc(hidden)]
38 const MATCH_ANY_EXACT: bool = false;
39
40 #[doc(hidden)]
42 fn match_any_exact_type_index() -> i32 {
43 unreachable!("MATCH_ANY_EXACT is false")
44 }
45
46 #[inline]
65 unsafe fn is_undefined(field: *const Self) -> bool {
66 let _ = field;
67 false
68 }
69
70 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
72 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny);
74 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool;
76
77 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
80 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
84 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
86 fn get_mismatch_type_info(data: &TVMFFIAny) -> String {
88 unsafe {
89 let info = TVMFFIGetTypeInfo(data.type_index);
90 assert!(!info.is_null(), "TVMFFIGetTypeInfo returned null");
91 (*info).type_key.as_str().to_string()
92 }
93 }
94 fn type_str() -> String;
96
97 fn type_schema() -> String {
104 type_schema(&Self::type_str(), &[])
105 }
106
107 #[inline]
115 fn to_any(&self) -> Any {
116 AnyView::from(self).into()
117 }
118}
119
120pub(crate) fn type_schema(origin: &str, args: &[String]) -> String {
123 if args.is_empty() {
124 format!(r#"{{"type":"{origin}"}}"#)
125 } else {
126 format!(r#"{{"type":"{origin}","args":[{}]}}"#, args.join(","))
127 }
128}
129
130pub(crate) fn type_schema_metadata(type_schema: &str) -> String {
133 format!(r#"{{"type_schema":{}}}"#, escape_string_json(type_schema))
134}
135
136fn escape_string_json(text: &str) -> String {
139 let mut out = String::with_capacity(text.len() + 2);
140 out.push('"');
141 for ch in text.chars() {
142 match ch {
143 '"' => out.push_str("\\\""),
144 '\\' => out.push_str("\\\\"),
145 '/' => out.push_str("\\/"),
146 '\u{8}' => out.push_str("\\b"),
147 '\u{c}' => out.push_str("\\f"),
148 '\n' => out.push_str("\\n"),
149 '\r' => out.push_str("\\r"),
150 '\t' => out.push_str("\\t"),
151 ch if (ch as u32) < 0x20 || ch == '\u{7f}' => {
152 out.push_str(&format!("\\u{:04x}", ch as u32))
153 }
154 ch => out.push(ch),
155 }
156 }
157 out.push('"');
158 out
159}
160
161pub(crate) trait TypeSchema {
167 fn type_schema() -> String;
168}
169
170impl<T: AnyCompatible> TypeSchema for T {
171 fn type_schema() -> String {
172 <T as AnyCompatible>::type_schema()
173 }
174}
175
176impl TypeSchema for Any {
177 fn type_schema() -> String {
178 type_schema("Any", &[])
179 }
180}
181
182impl TypeSchema for AnyView<'_> {
183 fn type_schema() -> String {
184 type_schema("Any", &[])
185 }
186}
187
188#[doc(hidden)]
198pub trait ContainerElement: container_element_ops::Ops {}
199
200impl<T: AnyCompatible> ContainerElement for T {}
201impl ContainerElement for Any {}
202
203mod container_element_ops {
204 use super::{Any, AnyCompatible, AnyView, TVMFFIAny};
205
206 pub trait Ops: Sized {
207 const CONTAINER_IS_ANY: bool = false;
208
209 unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
210 unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny);
211 unsafe fn container_check_any_strict(data: &TVMFFIAny) -> bool;
212 unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
213 unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
214 unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
215 fn container_get_mismatch_type_info(data: &TVMFFIAny) -> String;
216 fn container_type_str() -> String;
217 fn container_type_schema() -> String;
218 }
219
220 impl<T: AnyCompatible> Ops for T {
221 #[inline]
222 unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
223 <T as AnyCompatible>::copy_to_any_view(src, data)
224 }
225
226 #[inline]
227 unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny) {
228 <T as AnyCompatible>::move_to_any(src, data)
229 }
230
231 #[inline]
232 unsafe fn container_check_any_strict(data: &TVMFFIAny) -> bool {
233 <T as AnyCompatible>::check_any_strict(data)
234 }
235
236 #[inline]
237 unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
238 <T as AnyCompatible>::copy_from_any_view_after_check(data)
239 }
240
241 #[inline]
242 unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
243 <T as AnyCompatible>::move_from_any_after_check(data)
244 }
245
246 #[inline]
247 unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
248 <T as AnyCompatible>::try_cast_from_any_view(data)
249 }
250
251 #[inline]
252 fn container_get_mismatch_type_info(data: &TVMFFIAny) -> String {
253 <T as AnyCompatible>::get_mismatch_type_info(data)
254 }
255
256 #[inline]
257 fn container_type_str() -> String {
258 <T as AnyCompatible>::type_str()
259 }
260
261 #[inline]
262 fn container_type_schema() -> String {
263 <T as AnyCompatible>::type_schema()
264 }
265 }
266
267 impl Ops for Any {
268 const CONTAINER_IS_ANY: bool = true;
269
270 #[inline]
271 unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
272 *data = *src.as_raw_ffi_any();
273 }
274
275 #[inline]
276 unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny) {
277 *data = Any::into_raw_ffi_any(src);
278 }
279
280 #[inline]
281 unsafe fn container_check_any_strict(_data: &TVMFFIAny) -> bool {
282 true
283 }
284
285 #[inline]
286 unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
287 Any::from(AnyView::from_raw_ffi_any(*data))
288 }
289
290 #[inline]
291 unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
292 Any::from_raw_ffi_any(std::mem::replace(data, TVMFFIAny::new()))
293 }
294
295 #[inline]
296 unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
297 Ok(Any::from(AnyView::from_raw_ffi_any(*data)))
298 }
299
300 #[inline]
301 fn container_get_mismatch_type_info(_data: &TVMFFIAny) -> String {
302 "Any".to_string()
303 }
304
305 #[inline]
306 fn container_type_str() -> String {
307 "Any".to_string()
308 }
309
310 #[inline]
311 fn container_type_schema() -> String {
312 <Any as super::TypeSchema>::type_schema()
313 }
314 }
315}
316
317unsafe impl AnyCompatible for bool {
319 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
320 data.type_index = TypeIndex::kTVMFFIBool as i32;
321 data.small_str_len = 0;
322 data.data_union.v_int64 = *src as i64;
323 }
324 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
325 data.type_index == TypeIndex::kTVMFFIBool as i32
326 }
327
328 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
329 data.data_union.v_int64 != 0
330 }
331
332 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
333 data.type_index = TypeIndex::kTVMFFIBool as i32;
334 data.small_str_len = 0;
335 data.data_union.v_int64 = src as i64;
336 }
337
338 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
339 data.data_union.v_int64 != 0
340 }
341
342 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
343 if data.type_index == TypeIndex::kTVMFFIBool as i32
344 || data.type_index == TypeIndex::kTVMFFIInt as i32
345 {
346 unsafe { Ok(data.data_union.v_int64 != 0) }
347 } else {
348 Err(())
349 }
350 }
351
352 fn type_str() -> String {
353 "bool".to_string()
354 }
355}
356
357macro_rules! impl_any_compatible_for_int {
359 ($($int_type:ty),* $(,)?) => {
360 $(
361 unsafe impl AnyCompatible for $int_type {
362 fn type_str() -> String {
363 "int".to_string()
364 }
365
366 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
367 data.type_index = TypeIndex::kTVMFFIInt as i32;
368 data.small_str_len = 0;
369 data.data_union.v_int64 = *src as i64;
370 }
371
372 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
373 data.type_index == TypeIndex::kTVMFFIInt as i32
374 }
375
376 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
377 data.data_union.v_int64 as $int_type
378 }
379
380 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
381 data.type_index = TypeIndex::kTVMFFIInt as i32;
382 data.small_str_len = 0;
383 data.data_union.v_int64 = src as i64;
384 }
385
386 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
387 data.data_union.v_int64 as $int_type
388 }
389
390 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
391 if data.type_index == TypeIndex::kTVMFFIInt as i32 ||
392 data.type_index == TypeIndex::kTVMFFIBool as i32 {
393 Ok(data.data_union.v_int64 as $int_type)
394 } else {
395 Err(())
396 }
397 }
398 }
399 )*
400 };
401}
402
403impl_any_compatible_for_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
405
406unsafe impl<T: AnyCompatible> AnyCompatible for Option<T> {
408 fn type_str() -> String {
409 "Optional<".to_string() + T::type_str().as_str() + ">"
411 }
412
413 fn type_schema() -> String {
414 type_schema("Optional", &[<T as AnyCompatible>::type_schema()])
415 }
416
417 unsafe fn is_undefined(field: *const Self) -> bool {
418 if std::mem::size_of::<Self>() != std::mem::size_of::<T>() {
423 return false;
424 }
425 let none = std::mem::MaybeUninit::new(None::<T>);
426 T::is_undefined(field.cast::<T>()) && !T::is_undefined(none.as_ptr().cast::<T>())
427 }
428
429 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
430 if let Some(ref value) = src {
431 T::copy_to_any_view(value, data);
432 } else {
433 data.type_index = TypeIndex::kTVMFFINone as i32;
434 data.small_str_len = 0;
435 data.data_union.v_int64 = 0;
436 }
437 }
438
439 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
440 if let Some(value) = src {
441 T::move_to_any(value, data);
442 } else {
443 data.type_index = TypeIndex::kTVMFFINone as i32;
444 data.small_str_len = 0;
445 data.data_union.v_int64 = 0;
446 }
447 }
448
449 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
450 return T::check_any_strict(data) || data.type_index == TypeIndex::kTVMFFINone as i32;
451 }
452
453 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
454 if data.type_index == TypeIndex::kTVMFFINone as i32 {
455 None
456 } else {
457 Some(T::copy_from_any_view_after_check(data))
458 }
459 }
460
461 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
462 if data.type_index == TypeIndex::kTVMFFINone as i32 {
463 None
464 } else {
465 Some(T::move_from_any_after_check(data))
466 }
467 }
468
469 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
470 if data.type_index == TypeIndex::kTVMFFINone as i32 {
471 Ok(None)
472 } else {
473 T::try_cast_from_any_view(data).map(Some)
474 }
475 }
476}
477
478unsafe impl AnyCompatible for *mut core::ffi::c_void {
480 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
481 data.type_index = TypeIndex::kTVMFFIOpaquePtr as i32;
482 data.small_str_len = 0;
483 data.data_union.v_ptr = *src;
484 }
485 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
486 data.type_index == TypeIndex::kTVMFFIOpaquePtr as i32
487 }
488
489 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
490 data.data_union.v_ptr
491 }
492
493 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
494 data.type_index = TypeIndex::kTVMFFIOpaquePtr as i32;
495 data.small_str_len = 0;
496 data.data_union.v_int64 = src as i64;
497 }
498
499 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
500 data.data_union.v_ptr
501 }
502
503 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
504 if data.type_index == TypeIndex::kTVMFFINone as i32 {
505 Ok(std::ptr::null_mut())
506 } else if data.type_index == TypeIndex::kTVMFFIOpaquePtr as i32 {
507 unsafe { Ok(data.data_union.v_ptr) }
508 } else {
509 Err(())
510 }
511 }
512
513 fn type_str() -> String {
514 "void*".to_string()
515 }
516}
517
518macro_rules! impl_any_compatible_for_float {
520 ($($float_type:ty),* $(,)?) => {
521 $(
522 unsafe impl AnyCompatible for $float_type {
523 fn type_str() -> String {
524 "float".to_string()
525 }
526
527 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
528 data.type_index = TypeIndex::kTVMFFIFloat as i32;
529 data.small_str_len = 0;
530 data.data_union.v_float64 = *src as f64;
531 }
532
533 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
534 data.type_index == TypeIndex::kTVMFFIFloat as i32
535 }
536
537 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
538 data.data_union.v_float64 as $float_type
539 }
540
541 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
542 data.type_index = TypeIndex::kTVMFFIFloat as i32;
543 data.small_str_len = 0;
544 data.data_union.v_float64 = src as f64;
545 }
546
547 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
548 data.data_union.v_float64 as $float_type
549 }
550
551 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
552 if data.type_index == TypeIndex::kTVMFFIFloat as i32 {
553 Ok(data.data_union.v_float64 as $float_type)
554 } else if data.type_index == TypeIndex::kTVMFFIInt as i32 ||
555 data.type_index == TypeIndex::kTVMFFIBool as i32 {
556 Ok(data.data_union.v_int64 as $float_type)
557 } else {
558 Err(())
559 }
560 }
561 }
562 )*
563 };
564}
565
566impl_any_compatible_for_float!(f32, f64);
568
569unsafe impl AnyCompatible for () {
574 fn type_str() -> String {
575 "None".to_string()
577 }
578
579 unsafe fn copy_to_any_view(_src: &Self, data: &mut TVMFFIAny) {
580 data.type_index = TypeIndex::kTVMFFINone as i32;
581 data.small_str_len = 0;
582 data.data_union.v_int64 = 0;
583 }
584
585 unsafe fn move_to_any(_src: Self, data: &mut TVMFFIAny) {
586 data.type_index = TypeIndex::kTVMFFINone as i32;
587 data.small_str_len = 0;
588 data.data_union.v_int64 = 0;
589 }
590
591 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
592 return data.type_index == TypeIndex::kTVMFFINone as i32;
593 }
594
595 unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {
596 ()
597 }
598
599 unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {
600 ()
601 }
602
603 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
604 if data.type_index == TypeIndex::kTVMFFINone as i32 {
605 Ok(())
606 } else {
607 Err(())
608 }
609 }
610}