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
831
832
833
834
835
836
837
838
/*
 * 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.
 */
//! [`List`], a mutable sequence whose handles all see each change.
//!
//! A `List` is a shared handle, like `Rc<RefCell<Vec<T>>>`: cloning it bumps
//! the reference count, and a mutation through one handle is seen through all
//! of them. That is why the mutating methods take `&self`, and why elements
//! are returned by value rather than by reference. It is not synchronized, so
//! it is neither `Send` nor `Sync`.
//!
//! Converting an `Any` into a `List<T>` shares an `ffi.List` whose elements
//! are all `T`; an `ffi.Array`, or a list whose elements need converting, is
//! copied into a new list.
//!
//! A read checks and converts an element in its cell, in place. While it
//! does, the element type's
//! [`extra_check`](crate::object::ObjectRefAnyCompatible::extra_check) and
//! [`convert_fallback`](crate::object::ObjectRefAnyCompatible::convert_fallback),
//! and the `Drop` of a value the read releases, must not modify that list.

// `ListObj` mirrors C++ `ListObj` (`Object` followed by `TVMFFISeqCell`), so
// Rust reads and edits the element cells in place: reads, `List::set`,
// `List::insert`, `List::remove`, `List::remove_range`,
// `List::truncate`, `List::reverse`, `List::clear` and iteration touch
// the buffer directly, with no FFI call. The object and its element buffer
// are allocated by the C++ runtime (`ffi.List`), because the buffer is a
// separate allocation that `data_deleter` has to free with the allocator that
// produced it. For the same reason, growing a full buffer is left to C++
// (`ffi.ListReserve`), which the mutators call only when there is no spare
// capacity; the elements themselves are then written in place.

use std::cell::UnsafeCell;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::{Bound, RangeBounds};
use std::ptr;

use crate::any::TryFromTemp;
use crate::collections::map::element_view;
use crate::derive::Object;
use crate::object::{Object, ObjectArc};
use crate::type_traits::ContainerElement;
use crate::{Any, AnyCompatible, AnyView, Error, ObjectRefCore, Result};
use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};

/// The object behind a [`List`], laid out as the C++ `ListObj`. Unlike
/// `ffi.Array`, the element buffer `data` is a separate allocation that the
/// runtime replaces when the list grows.
#[repr(C)]
#[derive(Object)]
#[object(type_key = "ffi.List", unsafe type_index = TypeIndex::kTVMFFIList)]
pub struct ListObj {
    pub(crate) object: Object,
    // `List` mutates these through `&self` (`push`, `set`, growth), so they are
    // `UnsafeCell`s: a `&ListObj` borrowed by `downcast_ref` stays sound while
    // the list changes. `UnsafeCell` is `repr(transparent)`, so the layout is
    // C++ `ListObj`'s.
    /// Pointer to the start of the element buffer.
    data: UnsafeCell<*mut core::ffi::c_void>,
    size: UnsafeCell<i64>,
    capacity: UnsafeCell<i64>,
    /// Deleter for the element buffer.
    pub data_deleter: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
}

impl ListObj {
    /// The number of elements.
    #[inline]
    pub fn len(&self) -> usize {
        // SAFETY: a read of the length, which no call mutates concurrently.
        unsafe { *self.size.get() as usize }
    }

    /// Whether the list has no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The number of elements the buffer holds before it is reallocated.
    #[inline]
    pub fn capacity(&self) -> usize {
        // SAFETY: as for `len`.
        unsafe { *self.capacity.get() as usize }
    }

    /// Cell `index` of the buffer; the caller keeps `index` below `capacity`.
    #[inline]
    unsafe fn cell(this: *mut ListObj, index: usize) -> *mut TVMFFIAny {
        unsafe { ((*(*this).data.get()) as *mut TVMFFIAny).add(index) }
    }

    /// Drops the elements from the back down to `len`.
    unsafe fn truncate(this: *mut ListObj, len: usize) {
        while unsafe { (*(*this).size.get()) as usize } > len {
            unsafe { (*(*this).size.get()) -= 1 };
            unsafe { drop(take_cell(Self::cell(this, (*(*this).size.get()) as usize))) };
        }
    }
}

/// Moves the element out of `cell`; the caller overwrites the cell or drops
/// it from the list's accounting.
#[inline]
unsafe fn take_cell(cell: *mut TVMFFIAny) -> Any {
    unsafe { Any::from_raw_ffi_any(ptr::read(cell)) }
}

#[inline]
unsafe fn write_cell<T: ContainerElement>(cell: *mut TVMFFIAny, value: T) {
    let mut raw = TVMFFIAny::new();
    unsafe { T::container_move_to_any(value, &mut raw) };
    unsafe { ptr::write(cell, raw) };
}

/// The most elements a list buffer can hold: its byte size must fit in `isize`.
const MAX_CAPACITY: usize = isize::MAX as usize / std::mem::size_of::<TVMFFIAny>();

// The error paths stay out of line so the hot paths are small enough to inline.
#[cold]
#[inline(never)]
fn index_error<T>(what: &str) -> Result<T> {
    crate::bail!(
        crate::error::INDEX_ERROR,
        "List {} index out of bound",
        what
    )
}

#[cold]
#[inline(never)]
fn type_error<T: ContainerElement>(index: usize) -> Result<T> {
    crate::bail!(
        crate::error::TYPE_ERROR,
        "Failed to cast element at {} to {}",
        index,
        T::container_type_str()
    )
}

/// A mutable, reference-counted sequence of `T`, passed across languages as
/// `ffi.List`.
///
/// Cloning a `List` is cheap and yields a handle to the same list, so a change
/// through one handle is seen through every other. Methods take `&self`.
///
/// # Examples
///
/// ```
/// use tvm_ffi::List;
///
/// let list = List::<i64>::new();
/// list.push(1)?;
/// list.push(2)?;
/// assert_eq!(list.get(1)?, 2);
/// assert_eq!(list.len(), 2);
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[repr(C)]
pub struct List<T> {
    data: ObjectArc<ListObj>,
    _marker: PhantomData<T>,
}

impl<T> Clone for List<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            _marker: PhantomData,
        }
    }
}

/// A list upcasts to the root [`ObjectRef`](crate::object::ObjectRef).
impl<T: ContainerElement> From<List<T>> for crate::object::ObjectRef {
    #[inline]
    fn from(value: List<T>) -> Self {
        crate::object::into_root_object_ref(value)
    }
}

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

impl<T: ContainerElement> TryFrom<&crate::object::ObjectRef> for List<T> {
    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<T: ContainerElement> ObjectRefCore for List<T> {
    type ContainerType = ListObj;

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

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

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

/// The elements of the `ffi.List` or `ffi.Array` object `data` holds; both
/// share the `TVMFFISeqCell` layout, so this is the one accessor for either.
///
/// # Safety
/// `data` must hold one of those two objects, and the list must not be
/// mutated while the slice is alive.
pub(crate) unsafe fn seq_cells(data: &TVMFFIAny) -> &[TVMFFIAny] {
    let seq = unsafe { &*(data.data_union.v_obj as *const ListObj) };
    unsafe {
        crate::util::slice_from_nullable_raw_parts(
            *seq.data.get() as *const TVMFFIAny,
            *seq.size.get() as usize,
        )
    }
}

impl<T: ContainerElement> List<T> {
    /// Creates an empty list.
    pub fn new() -> Self {
        Self::from_items(&[]).expect("ffi.List() failed to construct an empty list")
    }

    /// Builds a list by calling the runtime's `ffi.List` constructor.
    fn from_items(items: &[T]) -> Result<Self> {
        let args: Vec<AnyView<'_>> = items.iter().map(element_view).collect();
        let result = crate::cached_global_func!("ffi.List").call_packed(&args)?;
        // The runtime returns a fresh `ffi.List` of exactly these elements, so
        // take it without re-checking them.
        unsafe {
            debug_assert_eq!(
                result.as_raw_ffi_any().type_index,
                TypeIndex::kTVMFFIList as i32
            );
            let mut result = std::mem::ManuallyDrop::new(result);
            Ok(Self::move_from_any_after_check(
                &mut *result.as_raw_ffi_any_mut(),
            ))
        }
    }

    #[inline]
    fn obj(&self) -> *mut ListObj {
        ObjectArc::as_ptr(&self.data) as *mut ListObj
    }

    /// Returns the number of elements.
    #[inline]
    pub fn len(&self) -> usize {
        // SAFETY: a read of the length; nothing mutates it during the call.
        unsafe { *self.data.size.get() as usize }
    }

    /// Returns `true` if the list contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the number of elements the buffer holds before it is reallocated.
    pub fn capacity(&self) -> usize {
        unsafe { *self.data.capacity.get() as usize }
    }

    /// Returns the element at `index`.
    #[inline]
    pub fn get(&self, index: usize) -> Result<T> {
        let obj = self.obj();
        // SAFETY: `index` is in bounds, and the conversion leaves the list
        // unchanged while it reads the cell (see the module docs).
        unsafe {
            if index >= (*(*obj).size.get()) as usize {
                return index_error("get");
            }
            match T::container_try_cast_from_any_view(&*ListObj::cell(obj, index)) {
                Ok(value) => Ok(value),
                Err(()) => type_error(index),
            }
        }
    }

    /// Replaces the element at `index`, as `vec[index] = value`.
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    #[inline]
    pub fn set(&self, index: usize, value: T) {
        let obj = self.obj();
        unsafe {
            let size = (*(*obj).size.get()) as usize;
            if index >= size {
                panic!("Index out of bounds: the len is {size} but the index is {index}");
            }
            let cell = ListObj::cell(obj, index);
            let old = take_cell(cell);
            write_cell(cell, value);
            drop(old);
        }
    }

    /// Appends `value` to the end of the list.
    #[inline]
    pub fn push(&self, value: T) -> Result<()> {
        self.reserve_for(1)?;
        let obj = self.obj();
        unsafe {
            write_cell(ListObj::cell(obj, (*(*obj).size.get()) as usize), value);
            (*(*obj).size.get()) += 1;
        }
        Ok(())
    }

    /// Inserts `value` at `index`, shifting the elements after it.
    pub fn insert(&self, index: usize, value: T) -> Result<()> {
        let size = self.len();
        if index > size {
            return index_error("insert");
        }
        self.reserve_for(1)?;
        let obj = self.obj();
        unsafe {
            let cell = ListObj::cell(obj, index);
            ptr::copy(cell, cell.add(1), size - index);
            write_cell(cell, value);
            (*(*obj).size.get()) += 1;
        }
        Ok(())
    }

    /// Removes and returns the element at `index`, shifting the elements after
    /// it. If that element is not a `T`, the list is left untouched.
    #[inline]
    pub fn remove(&self, index: usize) -> Result<T> {
        let obj = self.obj();
        unsafe {
            let size = (*(*obj).size.get()) as usize;
            if index >= size {
                return index_error("remove");
            }
            let cell = ListObj::cell(obj, index);
            // Convert first, so that a mismatch leaves the list untouched; the
            // conversion leaves the list unchanged (see the module docs).
            let (value, old) = if T::container_check_any_strict(&*cell) {
                let mut raw = ptr::read(cell);
                (T::container_move_from_any_after_check(&mut raw), None)
            } else {
                match T::container_try_cast_from_any_view(&*cell) {
                    Ok(value) => (value, Some(take_cell(cell))),
                    Err(()) => return type_error(index),
                }
            };
            if index + 1 < size {
                ptr::copy(cell.add(1), cell, size - index - 1);
            }
            (*(*obj).size.get()) -= 1;
            // The list is consistent again before the old element's `Drop`
            // runs, which may modify it.
            drop(old);
            Ok(value)
        }
    }

    /// Removes all elements, keeping the buffer.
    #[inline]
    pub fn clear(&self) {
        unsafe { ListObj::truncate(self.obj(), 0) }
    }

    /// Returns the first element, or `None` if the list is empty; a
    /// `TYPE_ERROR` as [`get`](Self::get) gives it.
    pub fn first(&self) -> Result<Option<T>> {
        match self.len() {
            0 => Ok(None),
            _ => self.get(0).map(Some),
        }
    }

    /// Returns the last element, or `None` if the list is empty; a
    /// `TYPE_ERROR` as [`get`](Self::get) gives it.
    pub fn last(&self) -> Result<Option<T>> {
        match self.len() {
            0 => Ok(None),
            len => self.get(len - 1).map(Some),
        }
    }

    /// Removes and returns the last element, or `None` if the list is empty;
    /// a `TYPE_ERROR` as [`remove`](Self::remove) gives it.
    pub fn pop(&self) -> Result<Option<T>> {
        match self.len() {
            0 => Ok(None),
            len => self.remove(len - 1).map(Some),
        }
    }

    /// Shortens the list to `len` elements, dropping the rest; a no-op when it
    /// is already that short.
    pub fn truncate(&self, len: usize) {
        unsafe { ListObj::truncate(self.obj(), len) }
    }

    /// Removes the elements in `range`, shifting the ones after them, as
    /// [`Vec::drain`] does without returning them.
    ///
    /// # Panics
    ///
    /// Panics if `range` starts after it ends or ends past the list.
    pub fn remove_range(&self, range: impl RangeBounds<usize>) {
        let obj = self.obj();
        unsafe {
            let size = (*(*obj).size.get()) as usize;
            let start = match range.start_bound() {
                Bound::Included(&start) => start,
                Bound::Excluded(&start) => start
                    .checked_add(1)
                    .expect("attempted to index slice from after maximum usize"),
                Bound::Unbounded => 0,
            };
            let end = match range.end_bound() {
                Bound::Included(&end) => end
                    .checked_add(1)
                    .expect("attempted to index slice up to maximum usize"),
                Bound::Excluded(&end) => end,
                Bound::Unbounded => size,
            };
            if start > end {
                panic!("slice index starts at {start} but ends at {end}");
            }
            if end > size {
                panic!("range end index {end} out of range for slice of length {size}");
            }
            if start == end {
                return;
            }
            // Rotate the removed cells to the back and drop them from there,
            // so the list is consistent while each element is released.
            std::slice::from_raw_parts_mut(ListObj::cell(obj, start), size - start)
                .rotate_left(end - start);
            ListObj::truncate(obj, size - (end - start));
        }
    }

    /// Inserts every item of `iter`, in order, at `index`, shifting the
    /// elements after it.
    pub fn insert_many<I: IntoIterator<Item = T>>(&self, index: usize, iter: I) -> Result<()> {
        // Drain the iterator first: it may reach this same list through
        // another handle, so the length is only read once it is done.
        let items: Vec<T> = iter.into_iter().collect();
        let size = self.len();
        if index > size {
            return index_error("insert_many");
        }
        let count = items.len();
        if count == 0 {
            return Ok(());
        }
        self.reserve_for(count)?;
        let obj = self.obj();
        unsafe {
            let cell = ListObj::cell(obj, index);
            ptr::copy(cell, cell.add(count), size - index);
            for (offset, item) in items.into_iter().enumerate() {
                write_cell(cell.add(offset), item);
            }
            (*(*obj).size.get()) += count as i64;
        }
        Ok(())
    }

    /// Makes room for at least `additional` more elements without
    /// reallocating again, like `Vec::reserve`.
    pub fn reserve(&self, additional: usize) -> Result<()> {
        let total = self.len().saturating_add(additional);
        if total > self.capacity() {
            self.grow_to(total)?;
        }
        Ok(())
    }

    /// Makes room for `extra` more elements, growing geometrically so that
    /// repeated pushes take amortized constant time.
    #[inline]
    fn reserve_for(&self, extra: usize) -> Result<()> {
        let (size, capacity) = (self.len(), self.capacity());
        let needed = size.saturating_add(extra);
        if needed > capacity {
            self.grow_to((capacity * 2).min(MAX_CAPACITY).max(needed))?;
        }
        Ok(())
    }

    /// Has the runtime grow the buffer to hold `capacity` elements, with
    /// the allocator that owns it (`ffi.ListReserve`).
    #[cold]
    #[inline(never)]
    fn grow_to(&self, capacity: usize) -> Result<()> {
        if capacity > MAX_CAPACITY {
            crate::bail!(
                crate::error::VALUE_ERROR,
                "List capacity {} exceeds the maximum {}",
                capacity,
                MAX_CAPACITY
            );
        }
        crate::cached_global_func!("ffi.ListReserve")
            .call_packed(&[AnyView::from(self), AnyView::from(&(capacity as i64))])?;
        Ok(())
    }

    /// Appends every item of `iter`, in order.
    pub fn extend<I: IntoIterator<Item = T>>(&self, iter: I) -> Result<()> {
        let items: Vec<T> = iter.into_iter().collect();
        self.insert_many(self.len(), items)
    }

    /// Resizes the list to `new_len` elements, dropping the tail or appending
    /// clones of `value`.
    pub fn resize(&self, new_len: usize, value: T) -> Result<()>
    where
        T: Clone,
    {
        let len = self.len();
        if new_len <= len {
            self.truncate(new_len);
            return Ok(());
        }
        self.extend(std::iter::repeat_n(value, new_len - len))
    }

    /// Reverses the elements in place.
    pub fn reverse(&self) {
        let obj = self.obj();
        unsafe {
            let size = (*(*obj).size.get()) as usize;
            if size > 1 {
                std::slice::from_raw_parts_mut(ListObj::cell(obj, 0), size).reverse();
            }
        }
    }

    /// Returns a double-ended iterator over the elements, yielding
    /// `Result<T>`; see [`Iter`].
    pub fn iter(&self) -> Iter<'_, T> {
        Iter {
            list: self,
            index: 0,
            back: usize::MAX,
        }
    }
}

impl<T: ContainerElement> Default for List<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Debug for List<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let full_name = std::any::type_name::<T>();
        let short_name = full_name.split("::").last().unwrap_or(full_name);
        write!(f, "List<{}>[{}]", short_name, unsafe {
            *self.data.size.get()
        })
    }
}

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

impl<T: ContainerElement> FromIterator<T> for List<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let items: Vec<T> = iter.into_iter().collect();
        Self::from_items(&items).expect("ffi.List() failed to construct a list")
    }
}

// --- Iterator ---

/// Iterator over a [`List`], created by [`List::iter`]. Each step yields
/// `Ok(T)`, or the `TYPE_ERROR` [`List::get`] would give when the element at
/// that position is not a `T` (another handle to the same list may have put
/// it there), and then moves on to the next element. It re-reads the length
/// on every step, so it stays in bounds if the list is mutated meanwhile;
/// iterating from the back (`rev`) pins the end at the first back step.
pub struct Iter<'a, T> {
    list: &'a List<T>,
    index: usize,
    /// One past the last position still to visit from the back; `usize::MAX`
    /// until `next_back` runs, so forward iteration follows the live length.
    back: usize,
}

impl<T: ContainerElement> Iter<'_, T> {
    #[inline]
    fn end(&self) -> usize {
        self.back.min(self.list.len())
    }

    /// # Safety
    /// `index` is below the list's length.
    #[inline]
    unsafe fn read(&self, index: usize) -> Result<T> {
        // SAFETY: the conversion leaves the list unchanged while it reads the
        // cell (see the module docs).
        match unsafe {
            T::container_try_cast_from_any_view(&*ListObj::cell(self.list.obj(), index))
        } {
            Ok(value) => Ok(value),
            Err(()) => type_error(index),
        }
    }
}

impl<T: ContainerElement> Iterator for Iter<'_, T> {
    type Item = Result<T>;

    #[inline]
    fn next(&mut self) -> Option<Result<T>> {
        if self.index >= self.end() {
            return None;
        }
        let index = self.index;
        self.index += 1;
        Some(unsafe { self.read(index) })
    }

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

impl<T: ContainerElement> DoubleEndedIterator for Iter<'_, T> {
    #[inline]
    fn next_back(&mut self) -> Option<Result<T>> {
        let end = self.end();
        if end <= self.index {
            return None;
        }
        self.back = end - 1;
        Some(unsafe { self.read(end - 1) })
    }
}

impl<'a, T: ContainerElement> IntoIterator for &'a List<T> {
    type Item = Result<T>;
    type IntoIter = Iter<'a, T>;

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

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

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

    fn type_str() -> String {
        format!("List<{}>", T::container_type_str())
    }

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

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        unsafe {
            data.type_index == TypeIndex::kTVMFFIList as i32
                && seq_cells(data)
                    .iter()
                    .all(|cell| T::container_check_any_strict(cell))
        }
    }

    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
        unsafe {
            seq_cells(data)
                .iter()
                .all(|cell| T::container_match_constraints(cell))
        }
    }

    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIList 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::kTVMFFIList 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 ListObj };
        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 ListObj };
        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, ()> {
        // Mirrors C++ `SeqTypeTraitsBase::TryCastFromAnyView`: `ffi.Array` is
        // the accepted other sequence type.
        if data.type_index != TypeIndex::kTVMFFIList as i32
            && data.type_index != TypeIndex::kTVMFFIArray as i32
        {
            return Err(());
        }

        // Fast path: a list whose elements all match shares 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: convert element by element into a new list. The
        // conversions leave the source sequence unchanged (see the module
        // docs), so the borrowed cells stay valid.
        let mut items = Vec::new();
        for cell in unsafe { seq_cells(data) } {
            unsafe { items.push(T::container_try_cast_from_any_view(cell)?) };
        }
        Self::from_items(&items).map_err(|_| ())
    }
}

// The cell's payload word is the single object pointer of the handle.
unsafe impl<T> crate::type_traits::RefFromAnyUnchecked for List<T>
where
    T: 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<T> crate::type_traits::DowncastRefFromAny for List<T>
where
    T: 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<T> crate::type_traits::DowncastRefFromObject for List<T>
where
    T: 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) }
    }
}

crate::impl_into_arg!(impl[T: ContainerElement] List<T>);

impl<'b, T: ContainerElement> TryFrom<&'b Any> for List<T> {
    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<T: ContainerElement> TryFrom<Any> for List<T> {
    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, T: ContainerElement> TryFrom<AnyView<'a>> for List<T> {
    type Error = Error;

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