1use std::borrow::Borrow;
33use std::fmt::Debug;
34use std::marker::PhantomData;
35use std::ops::Deref;
36
37use crate::IntoArg;
38use crate::any::TryFromTemp;
39use crate::derive::Object;
40use crate::extra::cold_init_lazy_lock::ColdInitLazyLock;
41use crate::function::Function;
42use crate::object::{Object, ObjectArc};
43use crate::type_traits::{ContainerElement, TypeSubsumes};
44use crate::{Any, AnyCompatible, AnyView, Error, ObjectRefCore, Result};
45use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
46use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};
47
48#[inline]
49pub(crate) fn element_view<T: ContainerElement>(value: &T) -> AnyView<'_> {
50 unsafe {
51 let mut data = TVMFFIAny::new();
52 T::container_copy_to_any_view(value, &mut data);
53 AnyView::from_raw_ffi_any(data)
54 }
55}
56
57static MISSING_OBJECT: ColdInitLazyLock<usize> = ColdInitLazyLock::new(|| {
61 let missing = Function::get_global("ffi.GetInvalidObject")
62 .and_then(|f| f.call_packed(&[]))
63 .expect("ffi.GetInvalidObject failed");
64 unsafe { missing.as_raw_ffi_any().data_union.v_obj as usize }
65});
66
67fn element_from_any<T: ContainerElement>(value: Any) -> Result<T> {
68 unsafe {
69 if T::container_check_any_strict(value.as_raw_ffi_any()) {
70 let mut value = std::mem::ManuallyDrop::new(value);
71 return Ok(T::container_move_from_any_after_check(
72 &mut *value.as_raw_ffi_any_mut(),
73 ));
74 }
75 T::container_try_cast_from_any_view(value.as_raw_ffi_any()).map_err(|()| {
76 let message = format!(
77 "Cannot convert from type `{}` to `{}`",
78 T::container_get_mismatch_type_info(value.as_raw_ffi_any()),
79 T::container_type_str()
80 );
81 Error::new(crate::error::TYPE_ERROR, &message)
82 })
83 }
84}
85
86#[repr(C)]
99#[derive(Object)]
100#[object(type_key = "ffi.Map", unsafe type_index = TypeIndex::kTVMFFIMap)]
101pub struct MapObj {
102 pub(crate) object: Object,
103 pub data: *mut core::ffi::c_void,
105 pub size: u64,
107 pub slots: u64,
109}
110
111#[repr(C)]
130pub struct Map<K, V> {
131 data: ObjectArc<MapObj>,
132 _marker: PhantomData<(K, V)>,
133}
134
135unsafe impl<K: Send + Sync, V: Send + Sync> Send for Map<K, V> {}
137unsafe impl<K: Send + Sync, V: Send + Sync> Sync for Map<K, V> {}
138
139impl<K, V> Clone for Map<K, V> {
142 fn clone(&self) -> Self {
143 Self {
144 data: self.data.clone(),
145 _marker: PhantomData,
146 }
147 }
148}
149
150impl<K, V> From<Map<K, V>> for crate::object::ObjectRef
152where
153 Map<K, V>: ObjectRefCore,
154{
155 #[inline]
156 fn from(value: Map<K, V>) -> Self {
157 crate::object::into_root_object_ref(value)
158 }
159}
160
161impl<K, V> TryFrom<crate::object::ObjectRef> for Map<K, V>
163where
164 Map<K, V>: ObjectRefCore,
165{
166 type Error = crate::error::Error;
167 #[inline]
168 fn try_from(value: crate::object::ObjectRef) -> crate::error::Result<Self> {
169 crate::object::root_try_into(value)
170 }
171}
172
173impl<K, V> TryFrom<&crate::object::ObjectRef> for Map<K, V>
174where
175 Map<K, V>: ObjectRefCore + crate::type_traits::DowncastRefFromObject,
176{
177 type Error = crate::error::Error;
178 #[inline]
179 fn try_from(value: &crate::object::ObjectRef) -> crate::error::Result<Self> {
180 crate::object::root_try_into_ref(value)
181 }
182}
183
184unsafe impl<K: ContainerElement, V: ContainerElement> ObjectRefCore for Map<K, V> {
185 type ContainerType = MapObj;
186
187 fn data(this: &Self) -> &ObjectArc<MapObj> {
188 &this.data
189 }
190
191 fn into_data(this: Self) -> ObjectArc<MapObj> {
192 this.data
193 }
194
195 unsafe fn from_data(data: ObjectArc<MapObj>) -> Self {
196 Self {
197 data,
198 _marker: PhantomData,
199 }
200 }
201}
202
203impl<K, V> Deref for Map<K, V> {
207 type Target = MapObj;
208 #[inline]
209 fn deref(&self) -> &MapObj {
210 &self.data
211 }
212}
213
214impl<K, V> Map<K, V>
215where
216 K: ContainerElement,
217 V: ContainerElement,
218{
219 pub fn new() -> Self {
221 Self::from_pairs(&[]).expect("ffi.Map() failed to construct an empty map")
222 }
223
224 fn from_pairs(pairs: &[(K, V)]) -> Result<Self> {
227 let mut args: Vec<AnyView<'_>> = Vec::with_capacity(pairs.len() * 2);
228 for (k, v) in pairs {
229 args.push(element_view(k));
230 args.push(element_view(v));
231 }
232 let result = crate::cached_global_func!("ffi.Map").call_packed(&args)?;
233 Self::try_from(result)
234 }
235
236 pub fn len(&self) -> usize {
238 self.size as usize
239 }
240
241 pub fn is_empty(&self) -> bool {
243 self.len() == 0
244 }
245
246 fn try_contains_key(&self, key: &K) -> Result<bool> {
249 let result = crate::cached_global_func!("ffi.MapCount")
250 .call_packed(&[AnyView::from(self), element_view(key)])?;
251 Ok(i64::try_from(result)? != 0)
252 }
253
254 #[inline]
264 fn debug_assert_key_type(&self) {
265 #[cfg(debug_assertions)]
266 {
267 if !self.is_empty() {
268 let functor = self.iter_functor();
269 let first_key = functor
270 .call_packed(&[AnyView::from(&0i64)])
271 .expect("map iterator: reading current key failed");
272 assert!(
273 unsafe { K::container_check_any_strict(first_key.as_raw_ffi_any()) },
274 "Map lookup: key type `{}` does not match the map's stored key type",
275 std::any::type_name::<K>(),
276 );
277 }
278 }
279 }
280
281 pub fn contains_key(&self, key: impl IntoArg<K>) -> Result<bool> {
292 let present = self.try_contains_key(key.into_arg().borrow())?;
293 if !present {
294 self.debug_assert_key_type();
295 }
296 Ok(present)
297 }
298
299 pub fn get(&self, key: impl IntoArg<K>) -> Result<Option<V>> {
314 let key = key.into_arg();
315 let result = crate::cached_global_func!("ffi.MapGetItemOrMissing")
316 .call_packed(&[AnyView::from(self), element_view(key.borrow())])?;
317 let raw = result.as_raw_ffi_any();
318 if raw.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32
319 && unsafe { raw.data_union.v_obj } as usize == *MISSING_OBJECT
320 {
321 self.debug_assert_key_type();
322 return Ok(None);
323 }
324 let value = element_from_any(result)?;
325 Ok(Some(value))
326 }
327
328 pub fn iter(&self) -> Iter<K, V> {
330 Iter(self.make_iter(|f| (iter_read::<K>(f, 0, "key"), iter_read::<V>(f, 1, "value"))))
331 }
332
333 pub fn keys(&self) -> Keys<K> {
335 Keys(self.make_iter(|f| iter_read::<K>(f, 0, "key")))
336 }
337
338 pub fn values(&self) -> Values<V> {
340 Values(self.make_iter(|f| iter_read::<V>(f, 1, "value")))
341 }
342
343 fn make_iter<T>(&self, read: fn(&Function) -> T) -> MapIter<T> {
347 let remaining = self.len();
348 MapIter {
349 functor: (remaining != 0).then(|| self.iter_functor()),
350 remaining,
351 _keepalive: self.data.clone(),
352 read,
353 }
354 }
355
356 fn iter_functor(&self) -> Function {
358 let result = crate::cached_global_func!("ffi.MapForwardIterFunctor")
359 .call_packed(&[AnyView::from(self)])
360 .expect("ffi.MapForwardIterFunctor call failed");
361 Function::try_from(result).expect("ffi.MapForwardIterFunctor returned a non-function")
362 }
363
364 fn try_raw_entries(&self) -> Result<Vec<(Any, Any)>> {
370 forward_entries(
371 crate::cached_global_func!("ffi.MapForwardIterFunctor"),
372 AnyView::from(self),
373 self.len(),
374 )
375 }
376
377 fn from_raw_entries(entries: Vec<(Any, Any)>) -> Result<Self> {
379 let mut pairs = Vec::with_capacity(entries.len());
380 for (k, v) in entries {
381 pairs.push((element_from_any::<K>(k)?, element_from_any::<V>(v)?));
382 }
383 Self::from_pairs(&pairs)
384 }
385}
386
387fn forward_entries(
390 iter_functor: &Function,
391 container: AnyView,
392 len: usize,
393) -> Result<Vec<(Any, Any)>> {
394 let mut entries = Vec::with_capacity(len);
395 let mut remaining = len;
396 if remaining == 0 {
397 return Ok(entries);
398 }
399 let functor = iter_functor
400 .call_packed(&[container])
401 .and_then(Function::try_from)?;
402 loop {
403 let k = functor.call_packed(&[AnyView::from(&0i64)])?;
404 let v = functor.call_packed(&[AnyView::from(&1i64)])?;
405 entries.push((k, v));
406 remaining -= 1;
407 if remaining == 0 {
408 return Ok(entries);
409 }
410 functor.call_packed(&[AnyView::from(&2i64)])?;
411 }
412}
413
414impl<K, V> Default for Map<K, V>
415where
416 K: ContainerElement,
417 V: ContainerElement,
418{
419 fn default() -> Self {
420 Self::new()
421 }
422}
423
424impl<K, V> Debug for Map<K, V>
425where
426 K: ContainerElement,
427 V: ContainerElement,
428{
429 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430 fn short(name: &str) -> &str {
431 name.split("::").last().unwrap_or(name)
432 }
433 write!(
434 f,
435 "Map<{}, {}>[{}]",
436 short(std::any::type_name::<K>()),
437 short(std::any::type_name::<V>()),
438 self.len()
439 )
440 }
441}
442
443impl<K: ContainerElement, V: ContainerElement> std::fmt::Display for Map<K, V> {
445 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446 std::fmt::Display::fmt(&AnyView::from_object(&**ObjectRefCore::data(self)), f)
447 }
448}
449
450impl<K, V> FromIterator<(K, V)> for Map<K, V>
451where
452 K: ContainerElement,
453 V: ContainerElement,
454{
455 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
458 let pairs: Vec<(K, V)> = iter.into_iter().collect();
459 Self::from_pairs(&pairs).expect("ffi.Map() failed to construct a map")
460 }
461}
462
463impl<K: ContainerElement, V: ContainerElement, const N: usize> From<[(K, V); N]> for Map<K, V> {
464 fn from(pairs: [(K, V); N]) -> Self {
465 Self::from_pairs(&pairs).expect("ffi.Map() failed to construct a map")
466 }
467}
468
469impl<K, V> From<&Map<K, V>> for Map<K, V> {
471 #[inline]
472 fn from(value: &Map<K, V>) -> Self {
473 value.clone()
474 }
475}
476
477impl<K, V> Map<K, V> {
478 #[inline(always)]
483 pub fn upcast<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(self) -> Map<KU, VU> {
484 Map {
485 data: self.data,
486 _marker: PhantomData,
487 }
488 }
489
490 #[inline(always)]
492 pub fn upcast_ref<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(&self) -> &Map<KU, VU> {
493 unsafe { &*(self as *const Self as *const Map<KU, VU>) }
496 }
497}
498
499impl<K, V, KU: TypeSubsumes<K>, VU: TypeSubsumes<V>> IntoArg<Map<KU, VU>> for Map<K, V> {
500 type Output = Map<KU, VU>;
501 #[inline(always)]
502 fn into_arg(self) -> Map<KU, VU> {
503 self.upcast()
504 }
505 #[inline(always)]
506 fn into_owned(self) -> Map<KU, VU> {
507 self.upcast()
508 }
509}
510
511impl<'a, K, V, KU: TypeSubsumes<K> + 'a, VU: TypeSubsumes<V> + 'a> IntoArg<Map<KU, VU>>
512 for &'a Map<K, V>
513{
514 type Output = &'a Map<KU, VU>;
515 #[inline(always)]
516 fn into_arg(self) -> &'a Map<KU, VU> {
517 self.upcast_ref()
518 }
519 #[inline(always)]
520 fn into_owned(self) -> Map<KU, VU> {
521 self.upcast_ref().clone()
522 }
523}
524
525fn iter_read<T: ContainerElement>(functor: &Function, command: i64, kind: &str) -> T {
539 let any = functor
540 .call_packed(&[AnyView::from(&command)])
541 .expect("map iterator: reading current element failed");
542 element_from_any(any)
543 .unwrap_or_else(|_| panic!("map iterator: {kind} does not match the map's {kind} type"))
544}
545
546fn iter_advance(functor: &Function, remaining: &mut usize) {
550 debug_assert!(
551 *remaining > 0,
552 "iter_advance called with no remaining entries"
553 );
554 *remaining -= 1;
555 if *remaining > 0 {
556 functor
557 .call_packed(&[AnyView::from(&2i64)])
558 .expect("map iterator: advancing failed");
559 }
560}
561
562struct MapIter<T> {
564 functor: Option<Function>,
567 remaining: usize,
568 _keepalive: ObjectArc<MapObj>,
569 read: fn(&Function) -> T,
571}
572
573impl<T> Iterator for MapIter<T> {
574 type Item = T;
575
576 fn next(&mut self) -> Option<T> {
577 if self.remaining == 0 {
578 return None;
579 }
580 let functor = self
582 .functor
583 .as_ref()
584 .expect("non-empty map iterator has a functor");
585 let item = (self.read)(functor);
586 iter_advance(functor, &mut self.remaining);
587 Some(item)
588 }
589
590 fn size_hint(&self) -> (usize, Option<usize>) {
591 (self.remaining, Some(self.remaining))
592 }
593}
594
595impl<T> ExactSizeIterator for MapIter<T> {}
596
597macro_rules! map_iterator {
598 ($(#[$doc:meta])* $name:ident<$($param:ident),+>, $item:ty) => {
599 $(#[$doc])*
600 pub struct $name<$($param),+>(MapIter<$item>);
601
602 impl<$($param),+> Iterator for $name<$($param),+> {
603 type Item = $item;
604
605 #[inline]
606 fn next(&mut self) -> Option<$item> {
607 self.0.next()
608 }
609
610 #[inline]
611 fn size_hint(&self) -> (usize, Option<usize>) {
612 self.0.size_hint()
613 }
614 }
615
616 impl<$($param),+> ExactSizeIterator for $name<$($param),+> {}
617 };
618}
619
620map_iterator!(
621 Iter<K, V>, (K, V)
623);
624map_iterator!(
625 Keys<K>, K
627);
628map_iterator!(
629 Values<V>, V
631);
632
633impl<K, V> IntoIterator for &Map<K, V>
634where
635 K: ContainerElement,
636 V: ContainerElement,
637{
638 type Item = (K, V);
639 type IntoIter = Iter<K, V>;
640
641 fn into_iter(self) -> Self::IntoIter {
642 self.iter()
643 }
644}
645
646unsafe impl<K, V> AnyCompatible for Map<K, V>
649where
650 K: ContainerElement,
651 V: ContainerElement,
652{
653 #[inline]
654 unsafe fn is_undefined(field: *const Self) -> bool {
655 unsafe { ObjectArc::is_null(std::ptr::addr_of!((*field).data)) }
656 }
657
658 fn type_str() -> String {
659 format!(
660 "Map<{}, {}>",
661 K::container_type_str(),
662 V::container_type_str()
663 )
664 }
665
666 fn type_schema() -> String {
667 crate::type_traits::type_schema(
668 <MapObj as crate::ObjectCore>::TYPE_KEY,
669 &[K::container_type_schema(), V::container_type_schema()],
670 )
671 }
672
673 unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
674 if data.type_index != TypeIndex::kTVMFFIMap as i32 {
678 return false;
679 }
680 let map = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
681 match map.try_raw_entries() {
682 Ok(entries) => entries.iter().all(|(k, v)| unsafe {
683 K::container_check_any_strict(k.as_raw_ffi_any())
684 && V::container_check_any_strict(v.as_raw_ffi_any())
685 }),
686 Err(_) => false,
687 }
688 }
689
690 unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
691 let map = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
692 match map.try_raw_entries() {
693 Ok(entries) => entries.iter().all(|(k, v)| unsafe {
694 K::container_match_constraints(k.as_raw_ffi_any())
695 && V::container_match_constraints(v.as_raw_ffi_any())
696 }),
697 Err(_) => false,
698 }
699 }
700
701 unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
702 data.type_index = TypeIndex::kTVMFFIMap as i32;
703 data.data_union.v_obj = ObjectArc::as_ptr(Self::data(src)) as *mut TVMFFIObject;
704 data.small_str_len = 0;
705 }
706
707 unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
708 data.type_index = TypeIndex::kTVMFFIMap as i32;
709 data.data_union.v_obj = ObjectArc::into_raw(Self::into_data(src)) as *mut TVMFFIObject;
710 data.small_str_len = 0;
711 }
712
713 unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
714 let ptr = unsafe { data.data_union.v_obj as *const MapObj };
715 unsafe { crate::object::unsafe_::inc_ref(ptr as *mut TVMFFIObject) };
716 unsafe { Self::from_data(ObjectArc::from_raw(ptr)) }
717 }
718
719 unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
720 let ptr = unsafe { data.data_union.v_obj as *const MapObj };
721 let obj = unsafe { Self::from_data(ObjectArc::from_raw(ptr)) };
722 data.type_index = TypeIndex::kTVMFFINone as i32;
723 data.data_union.v_int64 = 0;
724 obj
725 }
726
727 unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
728 if data.type_index == TypeIndex::kTVMFFIDict as i32 {
729 let len = unsafe { (*(data.data_union.v_obj as *const MapObj)).size as usize };
732 let entries = unsafe {
733 forward_entries(
734 crate::cached_global_func!("ffi.DictForwardIterFunctor"),
735 AnyView::from_raw_ffi_any(*data),
736 len,
737 )
738 .map_err(|_| ())?
739 };
740 return Self::from_raw_entries(entries).map_err(|_| ());
741 }
742 if data.type_index != TypeIndex::kTVMFFIMap as i32 {
743 return Err(());
744 }
745
746 if unsafe { <Self as AnyCompatible>::check_any_strict(data) } {
748 return Ok(unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) });
749 }
750
751 let src = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
754 let entries = src.try_raw_entries().map_err(|_| ())?;
755 Self::from_raw_entries(entries).map_err(|_| ())
756 }
757}
758
759unsafe impl<K, V> crate::type_traits::RefFromAnyUnchecked for Map<K, V>
761where
762 K: ContainerElement,
763 V: ContainerElement,
764{
765 #[inline(always)]
766 unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
767 unsafe { &*(core::ptr::addr_of!(cell.data_union) as *const Self) }
768 }
769}
770
771unsafe impl<K, V> crate::type_traits::DowncastRefFromAny for Map<K, V>
772where
773 K: ContainerElement,
774 V: ContainerElement,
775{
776 #[inline(always)]
777 unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
778 unsafe { crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
779 }
780}
781
782unsafe impl<K, V> crate::type_traits::DowncastRefFromObject for Map<K, V>
783where
784 K: ContainerElement,
785 V: ContainerElement,
786{
787 #[inline(always)]
788 unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
789 unsafe { crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
790 }
791}
792
793impl<'b, K, V> TryFrom<&'b Any> for Map<K, V>
794where
795 K: ContainerElement,
796 V: ContainerElement,
797{
798 type Error = Error;
799
800 fn try_from(value: &'b Any) -> Result<Self> {
801 let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
802 Ok(TryFromTemp::into_value(temp))
803 }
804}
805
806impl<K, V> TryFrom<Any> for Map<K, V>
807where
808 K: ContainerElement,
809 V: ContainerElement,
810{
811 type Error = Error;
812
813 fn try_from(value: Any) -> Result<Self> {
814 let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
815 Ok(TryFromTemp::into_value(temp))
816 }
817}
818
819impl<'a, K, V> TryFrom<AnyView<'a>> for Map<K, V>
820where
821 K: ContainerElement,
822 V: ContainerElement,
823{
824 type Error = Error;
825
826 fn try_from(value: AnyView<'a>) -> Result<Self> {
827 let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
828 Ok(TryFromTemp::into_value(temp))
829 }
830}