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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
/*
 * 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.
 */
//! [`Map`], an immutable hash map whose lookups run in the FFI runtime.
//!
//! Converting an `Any` into a `Map<K, V>` checks every entry; when an entry
//! is not a `K`/`V` as is, the entries are converted one by one into a new map.

// The `MapObj` header mirrors C++ `MapBaseObj`, so `Map::len` reads `size`
// directly (no FFI). The hash-table storage itself is an implementation detail,
// so lookups and iteration are delegated to the global functions the C++ runtime
// registers (`ffi.MapGetItemOrMissing`, `ffi.MapForwardIterFunctor`, ...): there is no
// Map-specific C ABI, and a Rust re-implementation would have to replicate the
// hashing (`AnyHash`/`AnyEqual`) and dense/small probing, just as the Python
// bindings also delegate.

use std::borrow::Borrow;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Deref;

use crate::IntoArg;
use crate::any::TryFromTemp;
use crate::derive::Object;
use crate::extra::cold_init_lazy_lock::ColdInitLazyLock;
use crate::function::Function;
use crate::object::{Object, ObjectArc};
use crate::type_traits::{ContainerElement, TypeSubsumes};
use crate::{Any, AnyCompatible, AnyView, Error, ObjectRefCore, Result};
use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};

#[inline]
pub(crate) fn element_view<T: ContainerElement>(value: &T) -> AnyView<'_> {
    unsafe {
        let mut data = TVMFFIAny::new();
        T::container_copy_to_any_view(value, &mut data);
        AnyView::from_raw_ffi_any(data)
    }
}

/// The address of the runtime's missing-value sentinel, which
/// `ffi.MapGetItemOrMissing` returns for an absent key. The sentinel lives for
/// the whole process, so its address identifies it.
static MISSING_OBJECT: ColdInitLazyLock<usize> = ColdInitLazyLock::new(|| {
    let missing = Function::get_global("ffi.GetInvalidObject")
        .and_then(|f| f.call_packed(&[]))
        .expect("ffi.GetInvalidObject failed");
    unsafe { missing.as_raw_ffi_any().data_union.v_obj as usize }
});

fn element_from_any<T: ContainerElement>(value: Any) -> Result<T> {
    unsafe {
        if T::container_check_any_strict(value.as_raw_ffi_any()) {
            let mut value = std::mem::ManuallyDrop::new(value);
            return Ok(T::container_move_from_any_after_check(
                &mut *value.as_raw_ffi_any_mut(),
            ));
        }
        T::container_try_cast_from_any_view(value.as_raw_ffi_any()).map_err(|()| {
            let message = format!(
                "Cannot convert from type `{}` to `{}`",
                T::container_get_mismatch_type_info(value.as_raw_ffi_any()),
                T::container_type_str()
            );
            Error::new(crate::error::TYPE_ERROR, &message)
        })
    }
}

/// The object behind a [`Map`]. The header fields are laid out as the C++
/// `MapBaseObj`, so [`Map::len`] reads `size` without an FFI call; the storage
/// `data` points to stays opaque.
//
// This is a partial mirror by design: `MapBaseObj` has one more trailing field
// after `slots_` (a `data_deleter_` function pointer), omitted here because this
// binding is read-only — it only reads fields up to `size`, which precede it,
// and never allocates a `MapObj` itself (the C++ runtime allocates the larger
// `Small`/`DenseMapBaseObj` subclass), so the trailing field is never touched.
// The layout also assumes `TVM_FFI_DEBUG_WITH_ABI_CHANGE` is off (the default):
// with that debug flag set, `MapBaseObj` gains a *leading* `state_marker` field
// that would shift every offset below.
#[repr(C)]
#[derive(Object)]
#[object(type_key = "ffi.Map", unsafe type_index = TypeIndex::kTVMFFIMap)]
pub struct MapObj {
    pub(crate) object: Object,
    /// Pointer to the (opaque) key/value storage region (`MapBaseObj::data_`).
    pub data: *mut core::ffi::c_void,
    /// Number of entries (`MapBaseObj::size_`).
    pub size: u64,
    /// Number of hash slots; the MSB is a small-map tag (`MapBaseObj::slots_`).
    pub slots: u64,
}

/// An immutable, reference-counted map from `K` to `V`, passed across
/// languages as `ffi.Map`.
///
/// Cloning a `Map` is cheap: it shares the same entries.
///
/// # Examples
///
/// ```
/// use tvm_ffi::{Map, String};
///
/// let map: Map<String, i64> = [(String::from("a"), 1), (String::from("b"), 2)]
///     .into_iter()
///     .collect();
/// assert_eq!(map.len(), 2);
/// assert_eq!(map.get("b")?, Some(2));
/// assert_eq!(map.get("c")?, None);
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[repr(C)]
pub struct Map<K, V> {
    data: ObjectArc<MapObj>,
    _marker: PhantomData<(K, V)>,
}

// SAFETY: a `Map` is immutable, so sharing it is as safe as sharing its entries.
unsafe impl<K: Send + Sync, V: Send + Sync> Send for Map<K, V> {}
unsafe impl<K: Send + Sync, V: Send + Sync> Sync for Map<K, V> {}

// Manual `Clone`: the data is the shared `ObjectArc`, so `Map<K, V>` is `Clone`
// regardless of whether `K`/`V` are (they are only phantom markers).
impl<K, V> Clone for Map<K, V> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            _marker: PhantomData,
        }
    }
}

/// A map upcasts to the root [`ObjectRef`](crate::object::ObjectRef).
impl<K, V> From<Map<K, V>> for crate::object::ObjectRef
where
    Map<K, V>: ObjectRefCore,
{
    #[inline]
    fn from(value: Map<K, V>) -> Self {
        crate::object::into_root_object_ref(value)
    }
}

/// The strict downcast from the root [`ObjectRef`](crate::object::ObjectRef).
impl<K, V> TryFrom<crate::object::ObjectRef> for Map<K, V>
where
    Map<K, V>: ObjectRefCore,
{
    type Error = crate::error::Error;
    #[inline]
    fn try_from(value: crate::object::ObjectRef) -> crate::error::Result<Self> {
        crate::object::root_try_into(value)
    }
}

impl<K, V> TryFrom<&crate::object::ObjectRef> for Map<K, V>
where
    Map<K, V>: ObjectRefCore + crate::type_traits::DowncastRefFromObject,
{
    type Error = crate::error::Error;
    #[inline]
    fn try_from(value: &crate::object::ObjectRef) -> crate::error::Result<Self> {
        crate::object::root_try_into_ref(value)
    }
}

unsafe impl<K: ContainerElement, V: ContainerElement> ObjectRefCore for Map<K, V> {
    type ContainerType = MapObj;

    fn data(this: &Self) -> &ObjectArc<MapObj> {
        &this.data
    }

    fn into_data(this: Self) -> ObjectArc<MapObj> {
        this.data
    }

    unsafe fn from_data(data: ObjectArc<MapObj>) -> Self {
        Self {
            data,
            _marker: PhantomData,
        }
    }
}

// A `Map<K, V>` is a counted handle to its `MapObj`, so it derefs to it (like
// `ObjectArc` does): methods can read header fields as `self.size` instead of
// `self.data.size`.
impl<K, V> Deref for Map<K, V> {
    type Target = MapObj;
    #[inline]
    fn deref(&self) -> &MapObj {
        &self.data
    }
}

impl<K, V> Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    /// Creates an empty map.
    pub fn new() -> Self {
        Self::from_pairs(&[]).expect("ffi.Map() failed to construct an empty map")
    }

    /// Builds a map by calling the runtime's `ffi.Map` constructor with a flattened
    /// `[k0, v0, k1, v1, ...]` argument list.
    fn from_pairs(pairs: &[(K, V)]) -> Result<Self> {
        let mut args: Vec<AnyView<'_>> = Vec::with_capacity(pairs.len() * 2);
        for (k, v) in pairs {
            args.push(element_view(k));
            args.push(element_view(v));
        }
        let result = crate::cached_global_func!("ffi.Map").call_packed(&args)?;
        Self::try_from(result)
    }

    /// Returns the number of entries.
    pub fn len(&self) -> usize {
        self.size as usize
    }

    /// Returns `true` if the map contains no entries.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns whether `key` is present, propagating any FFI error (e.g. a key
    /// the runtime cannot hash) rather than panicking.
    fn try_contains_key(&self, key: &K) -> Result<bool> {
        let result = crate::cached_global_func!("ffi.MapCount")
            .call_packed(&[AnyView::from(self), element_view(key)])?;
        Ok(i64::try_from(result)? != 0)
    }

    /// In debug builds, panics if `K` does not match the map's actual key type,
    /// checked against one stored key. Compiles to nothing in release, so
    /// [`Map::get`] and [`Map::contains_key`] stay one FFI call there.
    ///
    /// A pure key lookup *hashes* the key rather than retrieving one, so a wrong
    /// `K` simply fails to match and reads as "absent" — unlike [`Map::iter`],
    /// which retrieves keys and surfaces the mismatch. This assertion catches
    /// that misuse in dev/tests without taxing release lookups. Only meaningful
    /// on a miss (a hit already proves `K` matched a stored key).
    #[inline]
    fn debug_assert_key_type(&self) {
        #[cfg(debug_assertions)]
        {
            if !self.is_empty() {
                let functor = self.iter_functor();
                let first_key = functor
                    .call_packed(&[AnyView::from(&0i64)])
                    .expect("map iterator: reading current key failed");
                assert!(
                    unsafe { K::container_check_any_strict(first_key.as_raw_ffi_any()) },
                    "Map lookup: key type `{}` does not match the map's stored key type",
                    std::any::type_name::<K>(),
                );
            }
        }
    }

    /// Returns whether `key` is present.
    ///
    /// # Errors
    ///
    /// Returns an error if the runtime cannot look `key` up, such as when it
    /// is not hashable.
    ///
    /// The result for a `key` of another type than the map's keys is
    /// unspecified, as for [`Map::get`]. Code generic over `K` that passes a
    /// `&K` adds the bound `for<'a> &'a K: IntoArg<K>`.
    pub fn contains_key(&self, key: impl IntoArg<K>) -> Result<bool> {
        let present = self.try_contains_key(key.into_arg().borrow())?;
        if !present {
            self.debug_assert_key_type();
        }
        Ok(present)
    }

    /// Looks up `key`, returning `Ok(None)` if it is absent.
    ///
    /// # Errors
    ///
    /// Returns an error if the runtime cannot look `key` up, such as when it
    /// is not hashable, or if the value is not a `V`.
    ///
    /// The result for a `key` of another type than the map's keys is
    /// unspecified: it currently reads as absent, since a lookup hashes the key
    /// instead of reading a stored one. Debug builds assert against it.
    ///
    /// A `&str` key builds a temporary `String` for the runtime lookup. Code
    /// generic over `K` that passes a `&K` adds the bound
    /// `for<'a> &'a K: IntoArg<K>`.
    pub fn get(&self, key: impl IntoArg<K>) -> Result<Option<V>> {
        let key = key.into_arg();
        let result = crate::cached_global_func!("ffi.MapGetItemOrMissing")
            .call_packed(&[AnyView::from(self), element_view(key.borrow())])?;
        let raw = result.as_raw_ffi_any();
        if raw.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32
            && unsafe { raw.data_union.v_obj } as usize == *MISSING_OBJECT
        {
            self.debug_assert_key_type();
            return Ok(None);
        }
        let value = element_from_any(result)?;
        Ok(Some(value))
    }

    /// Returns an iterator over the `(key, value)` pairs of the map.
    pub fn iter(&self) -> Iter<K, V> {
        Iter(self.make_iter(|f| (iter_read::<K>(f, 0, "key"), iter_read::<V>(f, 1, "value"))))
    }

    /// Returns an iterator over the keys of the map.
    pub fn keys(&self) -> Keys<K> {
        Keys(self.make_iter(|f| iter_read::<K>(f, 0, "key")))
    }

    /// Returns an iterator over the values of the map.
    pub fn values(&self) -> Values<V> {
        Values(self.make_iter(|f| iter_read::<V>(f, 1, "value")))
    }

    /// Builds a `MapIter` whose `read` extracts each entry as `T`. The
    /// forward-iteration functor is requested only for a non-empty map, so
    /// iterating an empty map makes no FFI call and allocates no functor.
    fn make_iter<T>(&self, read: fn(&Function) -> T) -> MapIter<T> {
        let remaining = self.len();
        MapIter {
            functor: (remaining != 0).then(|| self.iter_functor()),
            remaining,
            _keepalive: self.data.clone(),
            read,
        }
    }

    /// Obtains a fresh stateful forward-iteration functor from the runtime.
    fn iter_functor(&self) -> Function {
        let result = crate::cached_global_func!("ffi.MapForwardIterFunctor")
            .call_packed(&[AnyView::from(self)])
            .expect("ffi.MapForwardIterFunctor call failed");
        Function::try_from(result).expect("ffi.MapForwardIterFunctor returned a non-function")
    }

    /// Reads all entries as raw `(Any, Any)` pairs without converting to
    /// `K`/`V`, propagating FFI failures instead of panicking (unlike the
    /// iterator API): this backs strict checks and the converting fallback in
    /// `try_cast_from_any_view`, which run during argument decoding where a
    /// panic could unwind across the C ABI.
    fn try_raw_entries(&self) -> Result<Vec<(Any, Any)>> {
        forward_entries(
            crate::cached_global_func!("ffi.MapForwardIterFunctor"),
            AnyView::from(self),
            self.len(),
        )
    }

    /// Converts raw entries one by one into a new map.
    fn from_raw_entries(entries: Vec<(Any, Any)>) -> Result<Self> {
        let mut pairs = Vec::with_capacity(entries.len());
        for (k, v) in entries {
            pairs.push((element_from_any::<K>(k)?, element_from_any::<V>(v)?));
        }
        Self::from_pairs(&pairs)
    }
}

/// The `len` entries of the map or dict `container`, read with the iterator
/// functor that `iter_functor` makes for it.
fn forward_entries(
    iter_functor: &Function,
    container: AnyView,
    len: usize,
) -> Result<Vec<(Any, Any)>> {
    let mut entries = Vec::with_capacity(len);
    let mut remaining = len;
    if remaining == 0 {
        return Ok(entries);
    }
    let functor = iter_functor
        .call_packed(&[container])
        .and_then(Function::try_from)?;
    loop {
        let k = functor.call_packed(&[AnyView::from(&0i64)])?;
        let v = functor.call_packed(&[AnyView::from(&1i64)])?;
        entries.push((k, v));
        remaining -= 1;
        if remaining == 0 {
            return Ok(entries);
        }
        functor.call_packed(&[AnyView::from(&2i64)])?;
    }
}

impl<K, V> Default for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> Debug for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fn short(name: &str) -> &str {
            name.split("::").last().unwrap_or(name)
        }
        write!(
            f,
            "Map<{}, {}>[{}]",
            short(std::any::type_name::<K>()),
            short(std::any::type_name::<V>()),
            self.len()
        )
    }
}

/// Formats the map as its `repr`; see [`AnyView`].
impl<K: ContainerElement, V: ContainerElement> std::fmt::Display for Map<K, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&AnyView::from_object(&**ObjectRefCore::data(self)), f)
    }
}

impl<K, V> FromIterator<(K, V)> for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    /// For duplicate keys, a later pair overwrites an earlier one, as in
    /// `HashMap`, so the resulting map may be smaller than the iterator.
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let pairs: Vec<(K, V)> = iter.into_iter().collect();
        Self::from_pairs(&pairs).expect("ffi.Map() failed to construct a map")
    }
}

impl<K: ContainerElement, V: ContainerElement, const N: usize> From<[(K, V); N]> for Map<K, V> {
    fn from(pairs: [(K, V); N]) -> Self {
        Self::from_pairs(&pairs).expect("ffi.Map() failed to construct a map")
    }
}

/// A reference-count bump, as `From<&T> for T` of an object reference.
impl<K, V> From<&Map<K, V>> for Map<K, V> {
    #[inline]
    fn from(value: &Map<K, V>) -> Self {
        value.clone()
    }
}

impl<K, V> Map<K, V> {
    /// View this map as a `Map<KU, VU>` without a copy, as C++
    /// `Map<KU, VU>(const Map<K, V>&)` does for bases `KU` and `VU`.
    ///
    /// It is a method, not `From`, for the reasons on [`Array::upcast`](crate::Array::upcast).
    #[inline(always)]
    pub fn upcast<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(self) -> Map<KU, VU> {
        Map {
            data: self.data,
            _marker: PhantomData,
        }
    }

    /// Borrow this map as a `Map<KU, VU>`, as [`upcast`](Self::upcast) does.
    #[inline(always)]
    pub fn upcast_ref<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(&self) -> &Map<KU, VU> {
        // SAFETY: both are `repr(C)` over one `ObjectArc<MapObj>`, and every
        // entry of `Map<K, V>` is a valid entry of `Map<KU, VU>`.
        unsafe { &*(self as *const Self as *const Map<KU, VU>) }
    }
}

impl<K, V, KU: TypeSubsumes<K>, VU: TypeSubsumes<V>> IntoArg<Map<KU, VU>> for Map<K, V> {
    type Output = Map<KU, VU>;
    #[inline(always)]
    fn into_arg(self) -> Map<KU, VU> {
        self.upcast()
    }
    #[inline(always)]
    fn into_owned(self) -> Map<KU, VU> {
        self.upcast()
    }
}

impl<'a, K, V, KU: TypeSubsumes<K> + 'a, VU: TypeSubsumes<V> + 'a> IntoArg<Map<KU, VU>>
    for &'a Map<K, V>
{
    type Output = &'a Map<KU, VU>;
    #[inline(always)]
    fn into_arg(self) -> &'a Map<KU, VU> {
        self.upcast_ref()
    }
    #[inline(always)]
    fn into_owned(self) -> Map<KU, VU> {
        self.upcast_ref().clone()
    }
}

// --- Iterators ---
//
// The functor from `ffi.MapForwardIterFunctor` does not keep the map alive, so
// each iterator carries an `ObjectArc<MapObj>` keepalive. Functor command codes:
// `0` = read key, `1` = read value, `2` = advance.
//
// These are `ExactSizeIterator`s, so a key/value not matching the declared
// `K`/`V` panics rather than ending iteration early (which would drop entries).
// Use [`Map::get`], which returns `Err` on a type mismatch, when the element
// types are uncertain.

/// Reads the functor's current key (`command` 0) or value (`command` 1) as `T`,
/// panicking on a type mismatch (see the note above on `ExactSizeIterator`).
fn iter_read<T: ContainerElement>(functor: &Function, command: i64, kind: &str) -> T {
    let any = functor
        .call_packed(&[AnyView::from(&command)])
        .expect("map iterator: reading current element failed");
    element_from_any(any)
        .unwrap_or_else(|_| panic!("map iterator: {kind} does not match the map's {kind} type"))
}

/// Consumes one entry: decrements `remaining` and advances the functor unless
/// the map is now exhausted. Callers must guard `remaining > 0` (every `next`
/// returns early when it hits 0), so the decrement can never underflow.
fn iter_advance(functor: &Function, remaining: &mut usize) {
    debug_assert!(
        *remaining > 0,
        "iter_advance called with no remaining entries"
    );
    *remaining -= 1;
    if *remaining > 0 {
        functor
            .call_packed(&[AnyView::from(&2i64)])
            .expect("map iterator: advancing failed");
    }
}

/// Forward iterator over a [`Map`], yielding `T` per entry.
struct MapIter<T> {
    /// `None` for an empty map (no functor is requested); `Some` while at least
    /// one entry remains to be yielded.
    functor: Option<Function>,
    remaining: usize,
    _keepalive: ObjectArc<MapObj>,
    /// Reads the current entry, only the key or value the iterator yields.
    read: fn(&Function) -> T,
}

impl<T> Iterator for MapIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if self.remaining == 0 {
            return None;
        }
        // `remaining > 0` implies `functor` is `Some` (see `Map::make_iter`).
        let functor = self
            .functor
            .as_ref()
            .expect("non-empty map iterator has a functor");
        let item = (self.read)(functor);
        iter_advance(functor, &mut self.remaining);
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<T> ExactSizeIterator for MapIter<T> {}

macro_rules! map_iterator {
    ($(#[$doc:meta])* $name:ident<$($param:ident),+>, $item:ty) => {
        $(#[$doc])*
        pub struct $name<$($param),+>(MapIter<$item>);

        impl<$($param),+> Iterator for $name<$($param),+> {
            type Item = $item;

            #[inline]
            fn next(&mut self) -> Option<$item> {
                self.0.next()
            }

            #[inline]
            fn size_hint(&self) -> (usize, Option<usize>) {
                self.0.size_hint()
            }
        }

        impl<$($param),+> ExactSizeIterator for $name<$($param),+> {}
    };
}

map_iterator!(
    /// Iterator over `(key, value)` pairs, created by [`Map::iter`].
    Iter<K, V>, (K, V)
);
map_iterator!(
    /// Iterator over keys, created by [`Map::keys`].
    Keys<K>, K
);
map_iterator!(
    /// Iterator over values, created by [`Map::values`].
    Values<V>, V
);

impl<K, V> IntoIterator for &Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    type Item = (K, V);
    type IntoIter = Iter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

// --- Any Type System Conversions ---

unsafe impl<K, V> AnyCompatible for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    #[inline]
    unsafe fn is_undefined(field: *const Self) -> bool {
        unsafe { ObjectArc::is_null(std::ptr::addr_of!((*field).data)) }
    }

    fn type_str() -> String {
        format!(
            "Map<{}, {}>",
            K::container_type_str(),
            V::container_type_str()
        )
    }

    fn type_schema() -> String {
        crate::type_traits::type_schema(
            <MapObj as crate::ObjectCore>::TYPE_KEY,
            &[K::container_type_schema(), V::container_type_schema()],
        )
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        // Mirrors C++ `CheckAnyStrict` (map_base.h): every entry must strictly
        // match `K`/`V`. An FFI failure reads as "no match" — this fn has no
        // error channel and must not panic (see `try_raw_entries`).
        if data.type_index != TypeIndex::kTVMFFIMap as i32 {
            return false;
        }
        let map = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
        match map.try_raw_entries() {
            Ok(entries) => entries.iter().all(|(k, v)| unsafe {
                K::container_check_any_strict(k.as_raw_ffi_any())
                    && V::container_check_any_strict(v.as_raw_ffi_any())
            }),
            Err(_) => false,
        }
    }

    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
        let map = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
        match map.try_raw_entries() {
            Ok(entries) => entries.iter().all(|(k, v)| unsafe {
                K::container_match_constraints(k.as_raw_ffi_any())
                    && V::container_match_constraints(v.as_raw_ffi_any())
            }),
            Err(_) => false,
        }
    }

    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIMap as i32;
        data.data_union.v_obj = ObjectArc::as_ptr(Self::data(src)) as *mut TVMFFIObject;
        data.small_str_len = 0;
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIMap as i32;
        data.data_union.v_obj = ObjectArc::into_raw(Self::into_data(src)) as *mut TVMFFIObject;
        data.small_str_len = 0;
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        let ptr = unsafe { data.data_union.v_obj as *const MapObj };
        unsafe { crate::object::unsafe_::inc_ref(ptr as *mut TVMFFIObject) };
        unsafe { Self::from_data(ObjectArc::from_raw(ptr)) }
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        let ptr = unsafe { data.data_union.v_obj as *const MapObj };
        let obj = unsafe { Self::from_data(ObjectArc::from_raw(ptr)) };
        data.type_index = TypeIndex::kTVMFFINone as i32;
        data.data_union.v_int64 = 0;
        obj
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFIDict as i32 {
            // A dict is mutable, so it converts by copy, as C++ `Map` accepts it.
            // `ffi.Dict` shares the `MapBaseObj` header.
            let len = unsafe { (*(data.data_union.v_obj as *const MapObj)).size as usize };
            let entries = unsafe {
                forward_entries(
                    crate::cached_global_func!("ffi.DictForwardIterFunctor"),
                    AnyView::from_raw_ffi_any(*data),
                    len,
                )
                .map_err(|_| ())?
            };
            return Self::from_raw_entries(entries).map_err(|_| ());
        }
        if data.type_index != TypeIndex::kTVMFFIMap as i32 {
            return Err(());
        }

        // Fast path: if all entries match strictly, we can just copy the reference.
        if unsafe { <Self as AnyCompatible>::check_any_strict(data) } {
            return Ok(unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) });
        }

        // Slow path: try to convert entry by entry into a new map, as C++
        // `TryCastFromAnyView` does.
        let src = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
        let entries = src.try_raw_entries().map_err(|_| ())?;
        Self::from_raw_entries(entries).map_err(|_| ())
    }
}

// The cell's payload word is the single object pointer of the handle.
unsafe impl<K, V> crate::type_traits::RefFromAnyUnchecked for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &*(core::ptr::addr_of!(cell.data_union) as *const Self) }
    }
}

unsafe impl<K, V> crate::type_traits::DowncastRefFromAny for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    #[inline(always)]
    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
        unsafe { crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
    }
}

unsafe impl<K, V> crate::type_traits::DowncastRefFromObject for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    #[inline(always)]
    unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
        unsafe { crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
    }
}

impl<'b, K, V> TryFrom<&'b Any> for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    type Error = Error;

    fn try_from(value: &'b Any) -> Result<Self> {
        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
        Ok(TryFromTemp::into_value(temp))
    }
}

impl<K, V> TryFrom<Any> for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    type Error = Error;

    fn try_from(value: Any) -> Result<Self> {
        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
        Ok(TryFromTemp::into_value(temp))
    }
}

impl<'a, K, V> TryFrom<AnyView<'a>> for Map<K, V>
where
    K: ContainerElement,
    V: ContainerElement,
{
    type Error = Error;

    fn try_from(value: AnyView<'a>) -> Result<Self> {
        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
        Ok(TryFromTemp::into_value(temp))
    }
}