Skip to main content

tvm_ffi/collections/
list.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//! [`List`], a mutable sequence whose handles all see each change.
20//!
21//! A `List` is a shared handle, like `Rc<RefCell<Vec<T>>>`: cloning it bumps
22//! the reference count, and a mutation through one handle is seen through all
23//! of them. That is why the mutating methods take `&self`, and why elements
24//! are returned by value rather than by reference. It is not synchronized, so
25//! it is neither `Send` nor `Sync`.
26//!
27//! Converting an `Any` into a `List<T>` shares an `ffi.List` whose elements
28//! are all `T`; an `ffi.Array`, or a list whose elements need converting, is
29//! copied into a new list.
30//!
31//! A read checks and converts an element in its cell, in place. While it
32//! does, the element type's
33//! [`extra_check`](crate::object::ObjectRefAnyCompatible::extra_check) and
34//! [`convert_fallback`](crate::object::ObjectRefAnyCompatible::convert_fallback),
35//! and the `Drop` of a value the read releases, must not modify that list.
36
37// `ListObj` mirrors C++ `ListObj` (`Object` followed by `TVMFFISeqCell`), so
38// Rust reads and edits the element cells in place: reads, `List::set`,
39// `List::insert`, `List::remove`, `List::remove_range`,
40// `List::truncate`, `List::reverse`, `List::clear` and iteration touch
41// the buffer directly, with no FFI call. The object and its element buffer
42// are allocated by the C++ runtime (`ffi.List`), because the buffer is a
43// separate allocation that `data_deleter` has to free with the allocator that
44// produced it. For the same reason, growing a full buffer is left to C++
45// (`ffi.ListReserve`), which the mutators call only when there is no spare
46// capacity; the elements themselves are then written in place.
47
48use std::cell::UnsafeCell;
49use std::fmt::Debug;
50use std::marker::PhantomData;
51use std::ops::{Bound, RangeBounds};
52use std::ptr;
53
54use crate::any::TryFromTemp;
55use crate::collections::map::element_view;
56use crate::derive::Object;
57use crate::object::{Object, ObjectArc};
58use crate::type_traits::ContainerElement;
59use crate::{Any, AnyCompatible, AnyView, Error, ObjectRefCore, Result};
60use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
61use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};
62
63/// The object behind a [`List`], laid out as the C++ `ListObj`. Unlike
64/// `ffi.Array`, the element buffer `data` is a separate allocation that the
65/// runtime replaces when the list grows.
66#[repr(C)]
67#[derive(Object)]
68#[object(type_key = "ffi.List", unsafe type_index = TypeIndex::kTVMFFIList)]
69pub struct ListObj {
70    pub(crate) object: Object,
71    // `List` mutates these through `&self` (`push`, `set`, growth), so they are
72    // `UnsafeCell`s: a `&ListObj` borrowed by `downcast_ref` stays sound while
73    // the list changes. `UnsafeCell` is `repr(transparent)`, so the layout is
74    // C++ `ListObj`'s.
75    /// Pointer to the start of the element buffer.
76    data: UnsafeCell<*mut core::ffi::c_void>,
77    size: UnsafeCell<i64>,
78    capacity: UnsafeCell<i64>,
79    /// Deleter for the element buffer.
80    pub data_deleter: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
81}
82
83impl ListObj {
84    /// The number of elements.
85    #[inline]
86    pub fn len(&self) -> usize {
87        // SAFETY: a read of the length, which no call mutates concurrently.
88        unsafe { *self.size.get() as usize }
89    }
90
91    /// Whether the list has no elements.
92    #[inline]
93    pub fn is_empty(&self) -> bool {
94        self.len() == 0
95    }
96
97    /// The number of elements the buffer holds before it is reallocated.
98    #[inline]
99    pub fn capacity(&self) -> usize {
100        // SAFETY: as for `len`.
101        unsafe { *self.capacity.get() as usize }
102    }
103
104    /// Cell `index` of the buffer; the caller keeps `index` below `capacity`.
105    #[inline]
106    unsafe fn cell(this: *mut ListObj, index: usize) -> *mut TVMFFIAny {
107        unsafe { ((*(*this).data.get()) as *mut TVMFFIAny).add(index) }
108    }
109
110    /// Drops the elements from the back down to `len`.
111    unsafe fn truncate(this: *mut ListObj, len: usize) {
112        while unsafe { (*(*this).size.get()) as usize } > len {
113            unsafe { (*(*this).size.get()) -= 1 };
114            unsafe { drop(take_cell(Self::cell(this, (*(*this).size.get()) as usize))) };
115        }
116    }
117}
118
119/// Moves the element out of `cell`; the caller overwrites the cell or drops
120/// it from the list's accounting.
121#[inline]
122unsafe fn take_cell(cell: *mut TVMFFIAny) -> Any {
123    unsafe { Any::from_raw_ffi_any(ptr::read(cell)) }
124}
125
126#[inline]
127unsafe fn write_cell<T: ContainerElement>(cell: *mut TVMFFIAny, value: T) {
128    let mut raw = TVMFFIAny::new();
129    unsafe { T::container_move_to_any(value, &mut raw) };
130    unsafe { ptr::write(cell, raw) };
131}
132
133/// The most elements a list buffer can hold: its byte size must fit in `isize`.
134const MAX_CAPACITY: usize = isize::MAX as usize / std::mem::size_of::<TVMFFIAny>();
135
136// The error paths stay out of line so the hot paths are small enough to inline.
137#[cold]
138#[inline(never)]
139fn index_error<T>(what: &str) -> Result<T> {
140    crate::bail!(
141        crate::error::INDEX_ERROR,
142        "List {} index out of bound",
143        what
144    )
145}
146
147#[cold]
148#[inline(never)]
149fn type_error<T: ContainerElement>(index: usize) -> Result<T> {
150    crate::bail!(
151        crate::error::TYPE_ERROR,
152        "Failed to cast element at {} to {}",
153        index,
154        T::container_type_str()
155    )
156}
157
158/// A mutable, reference-counted sequence of `T`, passed across languages as
159/// `ffi.List`.
160///
161/// Cloning a `List` is cheap and yields a handle to the same list, so a change
162/// through one handle is seen through every other. Methods take `&self`.
163///
164/// # Examples
165///
166/// ```
167/// use tvm_ffi::List;
168///
169/// let list = List::<i64>::new();
170/// list.push(1)?;
171/// list.push(2)?;
172/// assert_eq!(list.get(1)?, 2);
173/// assert_eq!(list.len(), 2);
174/// # Ok::<(), tvm_ffi::Error>(())
175/// ```
176#[repr(C)]
177pub struct List<T> {
178    data: ObjectArc<ListObj>,
179    _marker: PhantomData<T>,
180}
181
182impl<T> Clone for List<T> {
183    fn clone(&self) -> Self {
184        Self {
185            data: self.data.clone(),
186            _marker: PhantomData,
187        }
188    }
189}
190
191/// A list upcasts to the root [`ObjectRef`](crate::object::ObjectRef).
192impl<T: ContainerElement> From<List<T>> for crate::object::ObjectRef {
193    #[inline]
194    fn from(value: List<T>) -> Self {
195        crate::object::into_root_object_ref(value)
196    }
197}
198
199/// The strict downcast from the root [`ObjectRef`](crate::object::ObjectRef).
200impl<T: ContainerElement> TryFrom<crate::object::ObjectRef> for List<T> {
201    type Error = crate::error::Error;
202    #[inline]
203    fn try_from(value: crate::object::ObjectRef) -> crate::error::Result<Self> {
204        crate::object::root_try_into(value)
205    }
206}
207
208impl<T: ContainerElement> TryFrom<&crate::object::ObjectRef> for List<T> {
209    type Error = crate::error::Error;
210    #[inline]
211    fn try_from(value: &crate::object::ObjectRef) -> crate::error::Result<Self> {
212        crate::object::root_try_into_ref(value)
213    }
214}
215
216unsafe impl<T: ContainerElement> ObjectRefCore for List<T> {
217    type ContainerType = ListObj;
218
219    fn data(this: &Self) -> &ObjectArc<ListObj> {
220        &this.data
221    }
222
223    fn into_data(this: Self) -> ObjectArc<ListObj> {
224        this.data
225    }
226
227    unsafe fn from_data(data: ObjectArc<ListObj>) -> Self {
228        Self {
229            data,
230            _marker: PhantomData,
231        }
232    }
233}
234
235/// The elements of the `ffi.List` or `ffi.Array` object `data` holds; both
236/// share the `TVMFFISeqCell` layout, so this is the one accessor for either.
237///
238/// # Safety
239/// `data` must hold one of those two objects, and the list must not be
240/// mutated while the slice is alive.
241pub(crate) unsafe fn seq_cells(data: &TVMFFIAny) -> &[TVMFFIAny] {
242    let seq = unsafe { &*(data.data_union.v_obj as *const ListObj) };
243    unsafe {
244        crate::util::slice_from_nullable_raw_parts(
245            *seq.data.get() as *const TVMFFIAny,
246            *seq.size.get() as usize,
247        )
248    }
249}
250
251impl<T: ContainerElement> List<T> {
252    /// Creates an empty list.
253    pub fn new() -> Self {
254        Self::from_items(&[]).expect("ffi.List() failed to construct an empty list")
255    }
256
257    /// Builds a list by calling the runtime's `ffi.List` constructor.
258    fn from_items(items: &[T]) -> Result<Self> {
259        let args: Vec<AnyView<'_>> = items.iter().map(element_view).collect();
260        let result = crate::cached_global_func!("ffi.List").call_packed(&args)?;
261        // The runtime returns a fresh `ffi.List` of exactly these elements, so
262        // take it without re-checking them.
263        unsafe {
264            debug_assert_eq!(
265                result.as_raw_ffi_any().type_index,
266                TypeIndex::kTVMFFIList as i32
267            );
268            let mut result = std::mem::ManuallyDrop::new(result);
269            Ok(Self::move_from_any_after_check(
270                &mut *result.as_raw_ffi_any_mut(),
271            ))
272        }
273    }
274
275    #[inline]
276    fn obj(&self) -> *mut ListObj {
277        ObjectArc::as_ptr(&self.data) as *mut ListObj
278    }
279
280    /// Returns the number of elements.
281    #[inline]
282    pub fn len(&self) -> usize {
283        // SAFETY: a read of the length; nothing mutates it during the call.
284        unsafe { *self.data.size.get() as usize }
285    }
286
287    /// Returns `true` if the list contains no elements.
288    #[inline]
289    pub fn is_empty(&self) -> bool {
290        self.len() == 0
291    }
292
293    /// Returns the number of elements the buffer holds before it is reallocated.
294    pub fn capacity(&self) -> usize {
295        unsafe { *self.data.capacity.get() as usize }
296    }
297
298    /// Returns the element at `index`.
299    #[inline]
300    pub fn get(&self, index: usize) -> Result<T> {
301        let obj = self.obj();
302        // SAFETY: `index` is in bounds, and the conversion leaves the list
303        // unchanged while it reads the cell (see the module docs).
304        unsafe {
305            if index >= (*(*obj).size.get()) as usize {
306                return index_error("get");
307            }
308            match T::container_try_cast_from_any_view(&*ListObj::cell(obj, index)) {
309                Ok(value) => Ok(value),
310                Err(()) => type_error(index),
311            }
312        }
313    }
314
315    /// Replaces the element at `index`, as `vec[index] = value`.
316    ///
317    /// # Panics
318    ///
319    /// Panics if `index >= len`.
320    #[inline]
321    pub fn set(&self, index: usize, value: T) {
322        let obj = self.obj();
323        unsafe {
324            let size = (*(*obj).size.get()) as usize;
325            if index >= size {
326                panic!("Index out of bounds: the len is {size} but the index is {index}");
327            }
328            let cell = ListObj::cell(obj, index);
329            let old = take_cell(cell);
330            write_cell(cell, value);
331            drop(old);
332        }
333    }
334
335    /// Appends `value` to the end of the list.
336    #[inline]
337    pub fn push(&self, value: T) -> Result<()> {
338        self.reserve_for(1)?;
339        let obj = self.obj();
340        unsafe {
341            write_cell(ListObj::cell(obj, (*(*obj).size.get()) as usize), value);
342            (*(*obj).size.get()) += 1;
343        }
344        Ok(())
345    }
346
347    /// Inserts `value` at `index`, shifting the elements after it.
348    pub fn insert(&self, index: usize, value: T) -> Result<()> {
349        let size = self.len();
350        if index > size {
351            return index_error("insert");
352        }
353        self.reserve_for(1)?;
354        let obj = self.obj();
355        unsafe {
356            let cell = ListObj::cell(obj, index);
357            ptr::copy(cell, cell.add(1), size - index);
358            write_cell(cell, value);
359            (*(*obj).size.get()) += 1;
360        }
361        Ok(())
362    }
363
364    /// Removes and returns the element at `index`, shifting the elements after
365    /// it. If that element is not a `T`, the list is left untouched.
366    #[inline]
367    pub fn remove(&self, index: usize) -> Result<T> {
368        let obj = self.obj();
369        unsafe {
370            let size = (*(*obj).size.get()) as usize;
371            if index >= size {
372                return index_error("remove");
373            }
374            let cell = ListObj::cell(obj, index);
375            // Convert first, so that a mismatch leaves the list untouched; the
376            // conversion leaves the list unchanged (see the module docs).
377            let (value, old) = if T::container_check_any_strict(&*cell) {
378                let mut raw = ptr::read(cell);
379                (T::container_move_from_any_after_check(&mut raw), None)
380            } else {
381                match T::container_try_cast_from_any_view(&*cell) {
382                    Ok(value) => (value, Some(take_cell(cell))),
383                    Err(()) => return type_error(index),
384                }
385            };
386            if index + 1 < size {
387                ptr::copy(cell.add(1), cell, size - index - 1);
388            }
389            (*(*obj).size.get()) -= 1;
390            // The list is consistent again before the old element's `Drop`
391            // runs, which may modify it.
392            drop(old);
393            Ok(value)
394        }
395    }
396
397    /// Removes all elements, keeping the buffer.
398    #[inline]
399    pub fn clear(&self) {
400        unsafe { ListObj::truncate(self.obj(), 0) }
401    }
402
403    /// Returns the first element, or `None` if the list is empty; a
404    /// `TYPE_ERROR` as [`get`](Self::get) gives it.
405    pub fn first(&self) -> Result<Option<T>> {
406        match self.len() {
407            0 => Ok(None),
408            _ => self.get(0).map(Some),
409        }
410    }
411
412    /// Returns the last element, or `None` if the list is empty; a
413    /// `TYPE_ERROR` as [`get`](Self::get) gives it.
414    pub fn last(&self) -> Result<Option<T>> {
415        match self.len() {
416            0 => Ok(None),
417            len => self.get(len - 1).map(Some),
418        }
419    }
420
421    /// Removes and returns the last element, or `None` if the list is empty;
422    /// a `TYPE_ERROR` as [`remove`](Self::remove) gives it.
423    pub fn pop(&self) -> Result<Option<T>> {
424        match self.len() {
425            0 => Ok(None),
426            len => self.remove(len - 1).map(Some),
427        }
428    }
429
430    /// Shortens the list to `len` elements, dropping the rest; a no-op when it
431    /// is already that short.
432    pub fn truncate(&self, len: usize) {
433        unsafe { ListObj::truncate(self.obj(), len) }
434    }
435
436    /// Removes the elements in `range`, shifting the ones after them, as
437    /// [`Vec::drain`] does without returning them.
438    ///
439    /// # Panics
440    ///
441    /// Panics if `range` starts after it ends or ends past the list.
442    pub fn remove_range(&self, range: impl RangeBounds<usize>) {
443        let obj = self.obj();
444        unsafe {
445            let size = (*(*obj).size.get()) as usize;
446            let start = match range.start_bound() {
447                Bound::Included(&start) => start,
448                Bound::Excluded(&start) => start
449                    .checked_add(1)
450                    .expect("attempted to index slice from after maximum usize"),
451                Bound::Unbounded => 0,
452            };
453            let end = match range.end_bound() {
454                Bound::Included(&end) => end
455                    .checked_add(1)
456                    .expect("attempted to index slice up to maximum usize"),
457                Bound::Excluded(&end) => end,
458                Bound::Unbounded => size,
459            };
460            if start > end {
461                panic!("slice index starts at {start} but ends at {end}");
462            }
463            if end > size {
464                panic!("range end index {end} out of range for slice of length {size}");
465            }
466            if start == end {
467                return;
468            }
469            // Rotate the removed cells to the back and drop them from there,
470            // so the list is consistent while each element is released.
471            std::slice::from_raw_parts_mut(ListObj::cell(obj, start), size - start)
472                .rotate_left(end - start);
473            ListObj::truncate(obj, size - (end - start));
474        }
475    }
476
477    /// Inserts every item of `iter`, in order, at `index`, shifting the
478    /// elements after it.
479    pub fn insert_many<I: IntoIterator<Item = T>>(&self, index: usize, iter: I) -> Result<()> {
480        // Drain the iterator first: it may reach this same list through
481        // another handle, so the length is only read once it is done.
482        let items: Vec<T> = iter.into_iter().collect();
483        let size = self.len();
484        if index > size {
485            return index_error("insert_many");
486        }
487        let count = items.len();
488        if count == 0 {
489            return Ok(());
490        }
491        self.reserve_for(count)?;
492        let obj = self.obj();
493        unsafe {
494            let cell = ListObj::cell(obj, index);
495            ptr::copy(cell, cell.add(count), size - index);
496            for (offset, item) in items.into_iter().enumerate() {
497                write_cell(cell.add(offset), item);
498            }
499            (*(*obj).size.get()) += count as i64;
500        }
501        Ok(())
502    }
503
504    /// Makes room for at least `additional` more elements without
505    /// reallocating again, like `Vec::reserve`.
506    pub fn reserve(&self, additional: usize) -> Result<()> {
507        let total = self.len().saturating_add(additional);
508        if total > self.capacity() {
509            self.grow_to(total)?;
510        }
511        Ok(())
512    }
513
514    /// Makes room for `extra` more elements, growing geometrically so that
515    /// repeated pushes take amortized constant time.
516    #[inline]
517    fn reserve_for(&self, extra: usize) -> Result<()> {
518        let (size, capacity) = (self.len(), self.capacity());
519        let needed = size.saturating_add(extra);
520        if needed > capacity {
521            self.grow_to((capacity * 2).min(MAX_CAPACITY).max(needed))?;
522        }
523        Ok(())
524    }
525
526    /// Has the runtime grow the buffer to hold `capacity` elements, with
527    /// the allocator that owns it (`ffi.ListReserve`).
528    #[cold]
529    #[inline(never)]
530    fn grow_to(&self, capacity: usize) -> Result<()> {
531        if capacity > MAX_CAPACITY {
532            crate::bail!(
533                crate::error::VALUE_ERROR,
534                "List capacity {} exceeds the maximum {}",
535                capacity,
536                MAX_CAPACITY
537            );
538        }
539        crate::cached_global_func!("ffi.ListReserve")
540            .call_packed(&[AnyView::from(self), AnyView::from(&(capacity as i64))])?;
541        Ok(())
542    }
543
544    /// Appends every item of `iter`, in order.
545    pub fn extend<I: IntoIterator<Item = T>>(&self, iter: I) -> Result<()> {
546        let items: Vec<T> = iter.into_iter().collect();
547        self.insert_many(self.len(), items)
548    }
549
550    /// Resizes the list to `new_len` elements, dropping the tail or appending
551    /// clones of `value`.
552    pub fn resize(&self, new_len: usize, value: T) -> Result<()>
553    where
554        T: Clone,
555    {
556        let len = self.len();
557        if new_len <= len {
558            self.truncate(new_len);
559            return Ok(());
560        }
561        self.extend(std::iter::repeat_n(value, new_len - len))
562    }
563
564    /// Reverses the elements in place.
565    pub fn reverse(&self) {
566        let obj = self.obj();
567        unsafe {
568            let size = (*(*obj).size.get()) as usize;
569            if size > 1 {
570                std::slice::from_raw_parts_mut(ListObj::cell(obj, 0), size).reverse();
571            }
572        }
573    }
574
575    /// Returns a double-ended iterator over the elements, yielding
576    /// `Result<T>`; see [`Iter`].
577    pub fn iter(&self) -> Iter<'_, T> {
578        Iter {
579            list: self,
580            index: 0,
581            back: usize::MAX,
582        }
583    }
584}
585
586impl<T: ContainerElement> Default for List<T> {
587    fn default() -> Self {
588        Self::new()
589    }
590}
591
592impl<T> Debug for List<T> {
593    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594        let full_name = std::any::type_name::<T>();
595        let short_name = full_name.split("::").last().unwrap_or(full_name);
596        write!(f, "List<{}>[{}]", short_name, unsafe {
597            *self.data.size.get()
598        })
599    }
600}
601
602/// Formats the list as its `repr`; see [`AnyView`].
603impl<T: ContainerElement> std::fmt::Display for List<T> {
604    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
605        std::fmt::Display::fmt(&AnyView::from_object(&**ObjectRefCore::data(self)), f)
606    }
607}
608
609impl<T: ContainerElement> FromIterator<T> for List<T> {
610    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
611        let items: Vec<T> = iter.into_iter().collect();
612        Self::from_items(&items).expect("ffi.List() failed to construct a list")
613    }
614}
615
616// --- Iterator ---
617
618/// Iterator over a [`List`], created by [`List::iter`]. Each step yields
619/// `Ok(T)`, or the `TYPE_ERROR` [`List::get`] would give when the element at
620/// that position is not a `T` (another handle to the same list may have put
621/// it there), and then moves on to the next element. It re-reads the length
622/// on every step, so it stays in bounds if the list is mutated meanwhile;
623/// iterating from the back (`rev`) pins the end at the first back step.
624pub struct Iter<'a, T> {
625    list: &'a List<T>,
626    index: usize,
627    /// One past the last position still to visit from the back; `usize::MAX`
628    /// until `next_back` runs, so forward iteration follows the live length.
629    back: usize,
630}
631
632impl<T: ContainerElement> Iter<'_, T> {
633    #[inline]
634    fn end(&self) -> usize {
635        self.back.min(self.list.len())
636    }
637
638    /// # Safety
639    /// `index` is below the list's length.
640    #[inline]
641    unsafe fn read(&self, index: usize) -> Result<T> {
642        // SAFETY: the conversion leaves the list unchanged while it reads the
643        // cell (see the module docs).
644        match unsafe {
645            T::container_try_cast_from_any_view(&*ListObj::cell(self.list.obj(), index))
646        } {
647            Ok(value) => Ok(value),
648            Err(()) => type_error(index),
649        }
650    }
651}
652
653impl<T: ContainerElement> Iterator for Iter<'_, T> {
654    type Item = Result<T>;
655
656    #[inline]
657    fn next(&mut self) -> Option<Result<T>> {
658        if self.index >= self.end() {
659            return None;
660        }
661        let index = self.index;
662        self.index += 1;
663        Some(unsafe { self.read(index) })
664    }
665
666    #[inline]
667    fn size_hint(&self) -> (usize, Option<usize>) {
668        (0, Some(self.end().saturating_sub(self.index)))
669    }
670}
671
672impl<T: ContainerElement> DoubleEndedIterator for Iter<'_, T> {
673    #[inline]
674    fn next_back(&mut self) -> Option<Result<T>> {
675        let end = self.end();
676        if end <= self.index {
677            return None;
678        }
679        self.back = end - 1;
680        Some(unsafe { self.read(end - 1) })
681    }
682}
683
684impl<'a, T: ContainerElement> IntoIterator for &'a List<T> {
685    type Item = Result<T>;
686    type IntoIter = Iter<'a, T>;
687
688    fn into_iter(self) -> Self::IntoIter {
689        self.iter()
690    }
691}
692
693// --- Any Type System Conversions ---
694
695unsafe impl<T: ContainerElement> AnyCompatible for List<T> {
696    #[inline]
697    unsafe fn is_undefined(field: *const Self) -> bool {
698        unsafe { ObjectArc::is_null(std::ptr::addr_of!((*field).data)) }
699    }
700
701    fn type_str() -> String {
702        format!("List<{}>", T::container_type_str())
703    }
704
705    fn type_schema() -> String {
706        crate::type_traits::type_schema(
707            <ListObj as crate::ObjectCore>::TYPE_KEY,
708            &[T::container_type_schema()],
709        )
710    }
711
712    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
713        unsafe {
714            data.type_index == TypeIndex::kTVMFFIList as i32
715                && seq_cells(data)
716                    .iter()
717                    .all(|cell| T::container_check_any_strict(cell))
718        }
719    }
720
721    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
722        unsafe {
723            seq_cells(data)
724                .iter()
725                .all(|cell| T::container_match_constraints(cell))
726        }
727    }
728
729    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
730        data.type_index = TypeIndex::kTVMFFIList as i32;
731        data.data_union.v_obj = ObjectArc::as_ptr(Self::data(src)) as *mut TVMFFIObject;
732        data.small_str_len = 0;
733    }
734
735    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
736        data.type_index = TypeIndex::kTVMFFIList as i32;
737        data.data_union.v_obj = ObjectArc::into_raw(Self::into_data(src)) as *mut TVMFFIObject;
738        data.small_str_len = 0;
739    }
740
741    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
742        let ptr = unsafe { data.data_union.v_obj as *const ListObj };
743        unsafe { crate::object::unsafe_::inc_ref(ptr as *mut TVMFFIObject) };
744        unsafe { Self::from_data(ObjectArc::from_raw(ptr)) }
745    }
746
747    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
748        let ptr = unsafe { data.data_union.v_obj as *const ListObj };
749        let obj = unsafe { Self::from_data(ObjectArc::from_raw(ptr)) };
750        data.type_index = TypeIndex::kTVMFFINone as i32;
751        data.data_union.v_int64 = 0;
752        obj
753    }
754
755    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
756        // Mirrors C++ `SeqTypeTraitsBase::TryCastFromAnyView`: `ffi.Array` is
757        // the accepted other sequence type.
758        if data.type_index != TypeIndex::kTVMFFIList as i32
759            && data.type_index != TypeIndex::kTVMFFIArray as i32
760        {
761            return Err(());
762        }
763
764        // Fast path: a list whose elements all match shares the reference.
765        if unsafe { <Self as AnyCompatible>::check_any_strict(data) } {
766            return Ok(unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) });
767        }
768
769        // Slow path: convert element by element into a new list. The
770        // conversions leave the source sequence unchanged (see the module
771        // docs), so the borrowed cells stay valid.
772        let mut items = Vec::new();
773        for cell in unsafe { seq_cells(data) } {
774            unsafe { items.push(T::container_try_cast_from_any_view(cell)?) };
775        }
776        Self::from_items(&items).map_err(|_| ())
777    }
778}
779
780// The cell's payload word is the single object pointer of the handle.
781unsafe impl<T> crate::type_traits::RefFromAnyUnchecked for List<T>
782where
783    T: ContainerElement,
784{
785    #[inline(always)]
786    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
787        unsafe { &*(core::ptr::addr_of!(cell.data_union) as *const Self) }
788    }
789}
790
791unsafe impl<T> crate::type_traits::DowncastRefFromAny for List<T>
792where
793    T: ContainerElement,
794{
795    #[inline(always)]
796    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
797        unsafe { crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
798    }
799}
800
801unsafe impl<T> crate::type_traits::DowncastRefFromObject for List<T>
802where
803    T: ContainerElement,
804{
805    #[inline(always)]
806    unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
807        unsafe { crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
808    }
809}
810
811crate::impl_into_arg!(impl[T: ContainerElement] List<T>);
812
813impl<'b, T: ContainerElement> TryFrom<&'b Any> for List<T> {
814    type Error = Error;
815
816    fn try_from(value: &'b Any) -> Result<Self> {
817        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
818        Ok(TryFromTemp::into_value(temp))
819    }
820}
821
822impl<T: ContainerElement> TryFrom<Any> for List<T> {
823    type Error = Error;
824
825    fn try_from(value: Any) -> Result<Self> {
826        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
827        Ok(TryFromTemp::into_value(temp))
828    }
829}
830
831impl<'a, T: ContainerElement> TryFrom<AnyView<'a>> for List<T> {
832    type Error = Error;
833
834    fn try_from(value: AnyView<'a>) -> Result<Self> {
835        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
836        Ok(TryFromTemp::into_value(temp))
837    }
838}