Skip to main content

tvm_ffi/collections/
map.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//! [`Map`], an immutable hash map whose lookups run in the FFI runtime.
20//!
21//! Converting an `Any` into a `Map<K, V>` checks every entry; when an entry
22//! is not a `K`/`V` as is, the entries are converted one by one into a new map.
23
24// The `MapObj` header mirrors C++ `MapBaseObj`, so `Map::len` reads `size`
25// directly (no FFI). The hash-table storage itself is an implementation detail,
26// so lookups and iteration are delegated to the global functions the C++ runtime
27// registers (`ffi.MapGetItemOrMissing`, `ffi.MapForwardIterFunctor`, ...): there is no
28// Map-specific C ABI, and a Rust re-implementation would have to replicate the
29// hashing (`AnyHash`/`AnyEqual`) and dense/small probing, just as the Python
30// bindings also delegate.
31
32use 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
57/// The address of the runtime's missing-value sentinel, which
58/// `ffi.MapGetItemOrMissing` returns for an absent key. The sentinel lives for
59/// the whole process, so its address identifies it.
60static 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/// The object behind a [`Map`]. The header fields are laid out as the C++
87/// `MapBaseObj`, so [`Map::len`] reads `size` without an FFI call; the storage
88/// `data` points to stays opaque.
89//
90// This is a partial mirror by design: `MapBaseObj` has one more trailing field
91// after `slots_` (a `data_deleter_` function pointer), omitted here because this
92// binding is read-only — it only reads fields up to `size`, which precede it,
93// and never allocates a `MapObj` itself (the C++ runtime allocates the larger
94// `Small`/`DenseMapBaseObj` subclass), so the trailing field is never touched.
95// The layout also assumes `TVM_FFI_DEBUG_WITH_ABI_CHANGE` is off (the default):
96// with that debug flag set, `MapBaseObj` gains a *leading* `state_marker` field
97// that would shift every offset below.
98#[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    /// Pointer to the (opaque) key/value storage region (`MapBaseObj::data_`).
104    pub data: *mut core::ffi::c_void,
105    /// Number of entries (`MapBaseObj::size_`).
106    pub size: u64,
107    /// Number of hash slots; the MSB is a small-map tag (`MapBaseObj::slots_`).
108    pub slots: u64,
109}
110
111/// An immutable, reference-counted map from `K` to `V`, passed across
112/// languages as `ffi.Map`.
113///
114/// Cloning a `Map` is cheap: it shares the same entries.
115///
116/// # Examples
117///
118/// ```
119/// use tvm_ffi::{Map, String};
120///
121/// let map: Map<String, i64> = [(String::from("a"), 1), (String::from("b"), 2)]
122///     .into_iter()
123///     .collect();
124/// assert_eq!(map.len(), 2);
125/// assert_eq!(map.get("b")?, Some(2));
126/// assert_eq!(map.get("c")?, None);
127/// # Ok::<(), tvm_ffi::Error>(())
128/// ```
129#[repr(C)]
130pub struct Map<K, V> {
131    data: ObjectArc<MapObj>,
132    _marker: PhantomData<(K, V)>,
133}
134
135// SAFETY: a `Map` is immutable, so sharing it is as safe as sharing its entries.
136unsafe 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
139// Manual `Clone`: the data is the shared `ObjectArc`, so `Map<K, V>` is `Clone`
140// regardless of whether `K`/`V` are (they are only phantom markers).
141impl<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
150/// A map upcasts to the root [`ObjectRef`](crate::object::ObjectRef).
151impl<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
161/// The strict downcast from the root [`ObjectRef`](crate::object::ObjectRef).
162impl<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
203// A `Map<K, V>` is a counted handle to its `MapObj`, so it derefs to it (like
204// `ObjectArc` does): methods can read header fields as `self.size` instead of
205// `self.data.size`.
206impl<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    /// Creates an empty map.
220    pub fn new() -> Self {
221        Self::from_pairs(&[]).expect("ffi.Map() failed to construct an empty map")
222    }
223
224    /// Builds a map by calling the runtime's `ffi.Map` constructor with a flattened
225    /// `[k0, v0, k1, v1, ...]` argument list.
226    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    /// Returns the number of entries.
237    pub fn len(&self) -> usize {
238        self.size as usize
239    }
240
241    /// Returns `true` if the map contains no entries.
242    pub fn is_empty(&self) -> bool {
243        self.len() == 0
244    }
245
246    /// Returns whether `key` is present, propagating any FFI error (e.g. a key
247    /// the runtime cannot hash) rather than panicking.
248    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    /// In debug builds, panics if `K` does not match the map's actual key type,
255    /// checked against one stored key. Compiles to nothing in release, so
256    /// [`Map::get`] and [`Map::contains_key`] stay one FFI call there.
257    ///
258    /// A pure key lookup *hashes* the key rather than retrieving one, so a wrong
259    /// `K` simply fails to match and reads as "absent" — unlike [`Map::iter`],
260    /// which retrieves keys and surfaces the mismatch. This assertion catches
261    /// that misuse in dev/tests without taxing release lookups. Only meaningful
262    /// on a miss (a hit already proves `K` matched a stored key).
263    #[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    /// Returns whether `key` is present.
282    ///
283    /// # Errors
284    ///
285    /// Returns an error if the runtime cannot look `key` up, such as when it
286    /// is not hashable.
287    ///
288    /// The result for a `key` of another type than the map's keys is
289    /// unspecified, as for [`Map::get`]. Code generic over `K` that passes a
290    /// `&K` adds the bound `for<'a> &'a K: IntoArg<K>`.
291    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    /// Looks up `key`, returning `Ok(None)` if it is absent.
300    ///
301    /// # Errors
302    ///
303    /// Returns an error if the runtime cannot look `key` up, such as when it
304    /// is not hashable, or if the value is not a `V`.
305    ///
306    /// The result for a `key` of another type than the map's keys is
307    /// unspecified: it currently reads as absent, since a lookup hashes the key
308    /// instead of reading a stored one. Debug builds assert against it.
309    ///
310    /// A `&str` key builds a temporary `String` for the runtime lookup. Code
311    /// generic over `K` that passes a `&K` adds the bound
312    /// `for<'a> &'a K: IntoArg<K>`.
313    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    /// Returns an iterator over the `(key, value)` pairs of the map.
329    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    /// Returns an iterator over the keys of the map.
334    pub fn keys(&self) -> Keys<K> {
335        Keys(self.make_iter(|f| iter_read::<K>(f, 0, "key")))
336    }
337
338    /// Returns an iterator over the values of the map.
339    pub fn values(&self) -> Values<V> {
340        Values(self.make_iter(|f| iter_read::<V>(f, 1, "value")))
341    }
342
343    /// Builds a `MapIter` whose `read` extracts each entry as `T`. The
344    /// forward-iteration functor is requested only for a non-empty map, so
345    /// iterating an empty map makes no FFI call and allocates no functor.
346    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    /// Obtains a fresh stateful forward-iteration functor from the runtime.
357    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    /// Reads all entries as raw `(Any, Any)` pairs without converting to
365    /// `K`/`V`, propagating FFI failures instead of panicking (unlike the
366    /// iterator API): this backs strict checks and the converting fallback in
367    /// `try_cast_from_any_view`, which run during argument decoding where a
368    /// panic could unwind across the C ABI.
369    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    /// Converts raw entries one by one into a new map.
378    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
387/// The `len` entries of the map or dict `container`, read with the iterator
388/// functor that `iter_functor` makes for it.
389fn 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
443/// Formats the map as its `repr`; see [`AnyView`].
444impl<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    /// For duplicate keys, a later pair overwrites an earlier one, as in
456    /// `HashMap`, so the resulting map may be smaller than the iterator.
457    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
469/// A reference-count bump, as `From<&T> for T` of an object reference.
470impl<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    /// View this map as a `Map<KU, VU>` without a copy, as C++
479    /// `Map<KU, VU>(const Map<K, V>&)` does for bases `KU` and `VU`.
480    ///
481    /// It is a method, not `From`, for the reasons on [`Array::upcast`](crate::Array::upcast).
482    #[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    /// Borrow this map as a `Map<KU, VU>`, as [`upcast`](Self::upcast) does.
491    #[inline(always)]
492    pub fn upcast_ref<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(&self) -> &Map<KU, VU> {
493        // SAFETY: both are `repr(C)` over one `ObjectArc<MapObj>`, and every
494        // entry of `Map<K, V>` is a valid entry of `Map<KU, VU>`.
495        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
525// --- Iterators ---
526//
527// The functor from `ffi.MapForwardIterFunctor` does not keep the map alive, so
528// each iterator carries an `ObjectArc<MapObj>` keepalive. Functor command codes:
529// `0` = read key, `1` = read value, `2` = advance.
530//
531// These are `ExactSizeIterator`s, so a key/value not matching the declared
532// `K`/`V` panics rather than ending iteration early (which would drop entries).
533// Use [`Map::get`], which returns `Err` on a type mismatch, when the element
534// types are uncertain.
535
536/// Reads the functor's current key (`command` 0) or value (`command` 1) as `T`,
537/// panicking on a type mismatch (see the note above on `ExactSizeIterator`).
538fn 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
546/// Consumes one entry: decrements `remaining` and advances the functor unless
547/// the map is now exhausted. Callers must guard `remaining > 0` (every `next`
548/// returns early when it hits 0), so the decrement can never underflow.
549fn 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
562/// Forward iterator over a [`Map`], yielding `T` per entry.
563struct MapIter<T> {
564    /// `None` for an empty map (no functor is requested); `Some` while at least
565    /// one entry remains to be yielded.
566    functor: Option<Function>,
567    remaining: usize,
568    _keepalive: ObjectArc<MapObj>,
569    /// Reads the current entry, only the key or value the iterator yields.
570    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        // `remaining > 0` implies `functor` is `Some` (see `Map::make_iter`).
581        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    /// Iterator over `(key, value)` pairs, created by [`Map::iter`].
622    Iter<K, V>, (K, V)
623);
624map_iterator!(
625    /// Iterator over keys, created by [`Map::keys`].
626    Keys<K>, K
627);
628map_iterator!(
629    /// Iterator over values, created by [`Map::values`].
630    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
646// --- Any Type System Conversions ---
647
648unsafe 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        // Mirrors C++ `CheckAnyStrict` (map_base.h): every entry must strictly
675        // match `K`/`V`. An FFI failure reads as "no match" — this fn has no
676        // error channel and must not panic (see `try_raw_entries`).
677        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            // A dict is mutable, so it converts by copy, as C++ `Map` accepts it.
730            // `ffi.Dict` shares the `MapBaseObj` header.
731            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        // Fast path: if all entries match strictly, we can just copy the reference.
747        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        // Slow path: try to convert entry by entry into a new map, as C++
752        // `TryCastFromAnyView` does.
753        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
759// The cell's payload word is the single object pointer of the handle.
760unsafe 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}