Skip to main content

tvm_ffi/collections/
array.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//! [`Array`], an immutable sequence with copy-on-write updates.
20
21use std::fmt::Debug;
22use std::marker::PhantomData;
23
24use crate::IntoArg;
25use crate::any::TryFromTemp;
26use crate::collections::list::seq_cells;
27use crate::derive::Object;
28use crate::object::ObjectCoreWithExtraItems;
29use crate::object::{Object, ObjectArc};
30use crate::type_traits::{ContainerElement, RefFromAnyUnchecked, TypeSubsumes};
31use crate::{Any, AnyCompatible, AnyView, ObjectRefCore};
32use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
33use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};
34
35/// The object behind an [`Array`], laid out as the C++ `ArrayObj`.
36#[repr(C)]
37#[derive(Object)]
38#[object(type_key = "ffi.Array", unsafe type_index = TypeIndex::kTVMFFIArray)]
39pub struct ArrayObj {
40    pub(crate) object: Object,
41    /// The element buffer, `capacity` `TVMFFIAny` cells.
42    pub data: *mut core::ffi::c_void,
43    /// The number of initialized elements.
44    pub size: i64,
45    /// The number of cells in the buffer.
46    pub capacity: i64,
47    /// Optional custom deleter for the data pointer.
48    pub data_deleter: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
49}
50
51// A Rust-allocated array holds `capacity` cells inline, of which the first `size`
52// are initialized.
53unsafe impl ObjectCoreWithExtraItems for ArrayObj {
54    type ExtraItem = TVMFFIAny;
55    fn extra_items_count(this: &Self) -> usize {
56        this.capacity as usize
57    }
58}
59
60// Runs only for a Rust-allocated array; one allocated in C++ is released by its
61// own deleter.
62impl Drop for ArrayObj {
63    fn drop(&mut self) {
64        let cells = self.data as *const TVMFFIAny;
65        for i in 0..self.size as usize {
66            // SAFETY: the first `size` cells are initialized and owned by the array.
67            drop(unsafe { Any::from_raw_ffi_any(*cells.add(i)) });
68        }
69    }
70}
71
72/// A reference-counted sequence of `T` with value semantics, passed across
73/// languages as `ffi.Array`.
74///
75/// Cloning an `Array` is cheap: it shares the same elements. The mutators
76/// ([`push`], [`insert`], [`pop`], [`truncate`], [`set`]) are copy-on-write:
77/// they copy the elements when the array is shared, and write in place when
78/// this handle is the only reference, so other handles never see the change.
79/// Use [`List`] for a sequence whose changes all handles see.
80///
81/// [`List`]: crate::List
82/// [`push`]: Array::push
83/// [`insert`]: Array::insert
84/// [`pop`]: Array::pop
85/// [`truncate`]: Array::truncate
86/// [`set`]: Array::set
87///
88/// # Examples
89///
90/// ```
91/// use tvm_ffi::Array;
92///
93/// let mut array = Array::from_vec(vec![1_i64, 2, 3]);
94/// assert_eq!(array.len(), 3);
95/// assert_eq!(array.get(1), Some(2));
96/// assert_eq!(array.get(3), None);
97///
98/// let snapshot = array.clone();
99/// array.push(4);
100/// assert_eq!(array.len(), 4);
101/// assert_eq!(snapshot.len(), 3);
102///
103/// let doubled: Array<i64> = array.iter().map(|x| x * 2).collect();
104/// assert_eq!(doubled.iter().copied().collect::<Vec<_>>(), vec![2, 4, 6, 8]);
105/// ```
106#[repr(C)]
107#[derive(Clone)]
108pub struct Array<T> {
109    data: ObjectArc<ArrayObj>,
110    _marker: PhantomData<T>,
111}
112
113// SAFETY: a shared `Array` is never mutated (mutators copy unless this handle
114// is unique), so sharing it is as safe as sharing its elements.
115unsafe impl<T: Send + Sync> Send for Array<T> {}
116unsafe impl<T: Send + Sync> Sync for Array<T> {}
117
118impl<T: ContainerElement + Clone> Debug for Array<T> {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        let full_name = std::any::type_name::<T>();
121        let short_name = full_name.split("::").last().unwrap_or(full_name);
122        write!(f, "Array<{}>[{}]", short_name, self.len())
123    }
124}
125
126/// Formats the array as its `repr`; see [`AnyView`].
127impl<T: ContainerElement + Clone> std::fmt::Display for Array<T> {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        std::fmt::Display::fmt(&AnyView::from_object(&**ObjectRefCore::data(self)), f)
130    }
131}
132
133impl<T: ContainerElement + Clone> Default for Array<T> {
134    fn default() -> Self {
135        Self::new()
136    }
137}
138
139impl<T: ContainerElement + Clone> From<Vec<T>> for Array<T> {
140    fn from(items: Vec<T>) -> Self {
141        Self::from_vec(items)
142    }
143}
144
145impl<T: ContainerElement + Clone, const N: usize> From<[T; N]> for Array<T> {
146    fn from(items: [T; N]) -> Self {
147        Self::from_vec(items.into())
148    }
149}
150
151impl<T: ContainerElement + Clone> From<&[T]> for Array<T> {
152    fn from(items: &[T]) -> Self {
153        Self::from_vec(items.to_vec())
154    }
155}
156
157/// A reference-count bump, as `From<&T> for T` of an object reference.
158impl<T: ContainerElement + Clone> From<&Array<T>> for Array<T> {
159    #[inline]
160    fn from(value: &Array<T>) -> Self {
161        value.clone()
162    }
163}
164
165impl<T, U: TypeSubsumes<T>> IntoArg<Array<U>> for Array<T> {
166    type Output = Array<U>;
167    #[inline(always)]
168    fn into_arg(self) -> Array<U> {
169        self.upcast()
170    }
171    #[inline(always)]
172    fn into_owned(self) -> Array<U> {
173        self.upcast()
174    }
175}
176
177impl<'a, T, U: TypeSubsumes<T> + ContainerElement + Clone + 'a> IntoArg<Array<U>> for &'a Array<T> {
178    type Output = &'a Array<U>;
179    #[inline(always)]
180    fn into_arg(self) -> &'a Array<U> {
181        self.upcast_ref()
182    }
183    #[inline(always)]
184    fn into_owned(self) -> Array<U> {
185        self.upcast_ref().clone()
186    }
187}
188
189/// An array upcasts to the root [`ObjectRef`](crate::object::ObjectRef).
190impl<T: ContainerElement + Clone> From<Array<T>> for crate::object::ObjectRef {
191    #[inline]
192    fn from(value: Array<T>) -> Self {
193        crate::object::into_root_object_ref(value)
194    }
195}
196
197/// The strict downcast from the root [`ObjectRef`](crate::object::ObjectRef).
198impl<T: ContainerElement + Clone> TryFrom<crate::object::ObjectRef> for Array<T> {
199    type Error = crate::error::Error;
200    #[inline]
201    fn try_from(value: crate::object::ObjectRef) -> crate::error::Result<Self> {
202        crate::object::root_try_into(value)
203    }
204}
205
206impl<T: ContainerElement + Clone> TryFrom<&crate::object::ObjectRef> for Array<T> {
207    type Error = crate::error::Error;
208    #[inline]
209    fn try_from(value: &crate::object::ObjectRef) -> crate::error::Result<Self> {
210        crate::object::root_try_into_ref(value)
211    }
212}
213
214impl<T> Array<T> {
215    /// View this array as an `Array<U>` without a copy, as C++
216    /// `Array<U>(const Array<T>&)` does for a base `U` of `T`.
217    ///
218    /// It is a method, not `From`: `From<Array<T>> for Array<U>` would overlap
219    /// `From<T> for T` at `T = U` (E0119), and a crate that defines `T` and `U`
220    /// cannot implement it for `Array` either (orphan rule, E0117).
221    ///
222    /// ```
223    /// use tvm_ffi::object::{ObjectRef, ObjectRefCore};
224    /// use tvm_ffi::{Array, Shape};
225    ///
226    /// let shapes = Array::from([Shape::from([1_i64, 2])]);
227    /// let objects: Array<ObjectRef> = shapes.clone().upcast();
228    /// assert!(objects[0].same_as(&shapes[0]));
229    /// ```
230    #[inline(always)]
231    pub fn upcast<U: TypeSubsumes<T>>(self) -> Array<U> {
232        Array {
233            data: self.data,
234            _marker: PhantomData,
235        }
236    }
237
238    /// Borrow this array as an `Array<U>`, as [`upcast`](Self::upcast) does.
239    #[inline(always)]
240    pub fn upcast_ref<U: TypeSubsumes<T>>(&self) -> &Array<U> {
241        // SAFETY: `Array<T>` and `Array<U>` are both `repr(C)` over one
242        // `ObjectArc<ArrayObj>`, and every `T` cell is a valid `U` cell.
243        unsafe { &*(self as *const Self as *const Array<U>) }
244    }
245}
246
247unsafe impl<T: ContainerElement + Clone> ObjectRefCore for Array<T> {
248    type ContainerType = ArrayObj;
249
250    fn data(this: &Self) -> &ObjectArc<Self::ContainerType> {
251        &this.data
252    }
253
254    fn into_data(this: Self) -> ObjectArc<Self::ContainerType> {
255        this.data
256    }
257
258    unsafe fn from_data(data: ObjectArc<Self::ContainerType>) -> Self {
259        Self {
260            data,
261            _marker: PhantomData,
262        }
263    }
264}
265
266impl<T: ContainerElement + Clone> Array<T> {
267    /// Create an empty array.
268    ///
269    /// # Returns
270    ///
271    /// The empty array.
272    ///
273    /// See also [`Array::from_vec`].
274    pub fn new() -> Self {
275        Self::from_vec(Vec::new())
276    }
277
278    /// Create an array holding `items`, like `Array::from(items)`.
279    ///
280    /// # Arguments
281    ///
282    /// * `items` - The elements.
283    ///
284    /// # Returns
285    ///
286    /// The array.
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// use tvm_ffi::Array;
292    ///
293    /// let array = Array::from_vec(vec![1_i64, 2, 3]);
294    /// assert_eq!(array[1], 2);
295    /// ```
296    pub fn from_vec(items: Vec<T>) -> Self {
297        let capacity = items.len();
298        Self::new_with_capacity(items, capacity)
299    }
300
301    /// Append `value` to the end.
302    ///
303    /// See also [`List::push`](crate::List::push).
304    pub fn push(&mut self, value: T) {
305        let size = self.len();
306        let container = self.make_mut(size + 1);
307        // SAFETY: `make_mut` left room for one more cell past `size`.
308        unsafe { write_cell((container.data as *mut TVMFFIAny).add(size), value) };
309        container.size += 1;
310    }
311
312    /// Insert `value` at `index`, shifting the elements after it, as
313    /// [`Vec::insert`].
314    ///
315    /// # Panics
316    ///
317    /// Panics if `index > len`.
318    ///
319    /// See also [`List::insert`](crate::List::insert).
320    pub fn insert(&mut self, index: usize, value: T) {
321        let size = self.len();
322        if index > size {
323            panic!("insertion index (is {index}) should be <= len (is {size})");
324        }
325        let container = self.make_mut(size + 1);
326        // SAFETY: `make_mut` left room for one more cell; the tail moves up by one.
327        unsafe {
328            let cell = (container.data as *mut TVMFFIAny).add(index);
329            std::ptr::copy(cell, cell.add(1), size - index);
330            write_cell(cell, value);
331        }
332        container.size += 1;
333    }
334
335    /// Remove and return the last element, or `None` if the array is empty,
336    /// as [`Vec::pop`].
337    ///
338    /// See also [`List::pop`](crate::List::pop).
339    pub fn pop(&mut self) -> Option<T> {
340        let size = self.len();
341        if size == 0 {
342            return None;
343        }
344        let container = self.make_mut(size);
345        container.size -= 1;
346        // SAFETY: the last cell is initialized, holds a `T`, and is no longer
347        // counted by `size`, so it is moved out exactly once.
348        unsafe {
349            let mut cell = std::ptr::read((container.data as *const TVMFFIAny).add(size - 1));
350            debug_assert!(T::container_check_any_strict(&cell));
351            Some(T::container_move_from_any_after_check(&mut cell))
352        }
353    }
354
355    /// Shorten the array to `len` elements, dropping the rest; a no-op when it
356    /// is already that short.
357    ///
358    /// See also [`List::truncate`](crate::List::truncate).
359    pub fn truncate(&mut self, len: usize) {
360        let size = self.len();
361        if len >= size {
362            return;
363        }
364        let container = self.make_mut(size);
365        // Shrink `size` first, so a panicking element drop leaks rather than
366        // double-frees the remaining cells.
367        container.size = len as i64;
368        let cells = container.data as *const TVMFFIAny;
369        for i in len..size {
370            // SAFETY: cells `len..size` are initialized and no longer counted.
371            drop(unsafe { Any::from_raw_ffi_any(*cells.add(i)) });
372        }
373    }
374
375    /// Replace the element at `index`, as `vec[index] = value`.
376    ///
377    /// # Panics
378    ///
379    /// Panics if `index >= len`.
380    ///
381    /// See also [`List::set`](crate::List::set).
382    pub fn set(&mut self, index: usize, value: T) {
383        let size = self.len();
384        if index >= size {
385            panic!("Index out of bounds: the len is {size} but the index is {index}");
386        }
387        let container = self.make_mut(size);
388        // SAFETY: the cell at `index` is initialized; its old value is dropped
389        // after the new one is written.
390        unsafe {
391            let cell = (container.data as *mut TVMFFIAny).add(index);
392            let old = Any::from_raw_ffi_any(std::ptr::read(cell));
393            write_cell(cell, value);
394            drop(old);
395        }
396    }
397
398    /// Return the number of elements.
399    ///
400    /// # Returns
401    ///
402    /// The number of elements.
403    pub fn len(&self) -> usize {
404        self.data.size as usize
405    }
406
407    /// Return `true` if the array has no elements.
408    ///
409    /// # Returns
410    ///
411    /// `true` if the array has no elements.
412    pub fn is_empty(&self) -> bool {
413        self.len() == 0
414    }
415
416    /// Return the element at `index`, or `None` if it is out of bounds, as
417    /// [`slice::get`]. `array[index]` borrows it instead, and panics when out
418    /// of bounds.
419    pub fn get(&self, index: usize) -> Option<T> {
420        let cell = self.cells().get(index)?;
421        // SAFETY: every cell of an `Array<T>` holds a `T`, checked when the
422        // array is built.
423        Some(unsafe {
424            debug_assert!(T::container_check_any_strict(cell));
425            T::container_copy_from_any_view_after_check(cell)
426        })
427    }
428
429    /// An array of `items` with room for `capacity` elements.
430    fn new_with_capacity(items: Vec<T>, capacity: usize) -> Self {
431        let size = items.len();
432
433        // Allocate with capacity
434        // SAFETY: the cells are written below; those past `size` are never read.
435        let mut arc = unsafe {
436            ObjectArc::<ArrayObj>::new_with_extra_items(ArrayObj {
437                object: Object::new(),
438                data: core::ptr::null_mut(),
439                size: size as i64,
440                capacity: capacity as i64,
441                data_deleter: None,
442            })
443        };
444
445        unsafe {
446            let container = ObjectArc::as_mut_ptr(&mut arc);
447            let base_ptr = ArrayObj::extra_items_ptr(container);
448            (*container).data = base_ptr as *mut _;
449
450            for (i, item) in items.into_iter().enumerate() {
451                write_cell(base_ptr.add(i), item);
452            }
453        }
454        // SAFETY: `arc` was allocated and initialized above as an `Array<T>`.
455        unsafe { Self::from_data(arc) }
456    }
457
458    /// Make this handle the only reference to its cells, with room for at least
459    /// `capacity` of them, and return the container to edit in place.
460    fn make_mut(&mut self, capacity: usize) -> &mut ArrayObj {
461        // As C++ `Array::CopyOnWrite(reserve)`.
462        let unique = ObjectArc::is_unique(&self.data);
463        let current = self.data.capacity as usize;
464        if !unique || capacity > current {
465            let capacity = if capacity > current {
466                (current * 2).max(capacity)
467            } else {
468                current
469            };
470            self.copy_to_new_buffer(capacity, unique);
471        }
472        // SAFETY: this handle is now the only reference, so no one else observes
473        // the container while it is mutably borrowed.
474        unsafe { &mut *ObjectArc::as_mut_ptr(&mut self.data) }
475    }
476
477    /// Replace `self` with a unique array of `capacity` cells holding the same
478    /// elements: moved out of a `unique` source, otherwise each re-referenced.
479    fn copy_to_new_buffer(&mut self, capacity: usize, unique: bool) {
480        let size = self.len();
481        let mut grown = Self::new_with_capacity(Vec::new(), capacity);
482        let source = self.as_container().data as *const TVMFFIAny;
483        // SAFETY: `grown` is fresh with room for `size` cells. A unique source
484        // forgets the cells it moved; a shared one keeps its own references.
485        unsafe {
486            let target = ObjectArc::as_mut_ptr(&mut grown.data);
487            let cells = (*target).data as *mut TVMFFIAny;
488            if unique {
489                std::ptr::copy_nonoverlapping(source, cells, size);
490                (*ObjectArc::as_mut_ptr(&mut self.data)).size = 0;
491            } else {
492                for i in 0..size {
493                    let copy = Any::from(AnyView::from_raw_ffi_any(*source.add(i)));
494                    std::ptr::write(cells.add(i), Any::into_raw_ffi_any(copy));
495                }
496            }
497            (*target).size = size as i64;
498        }
499        *self = grown;
500    }
501
502    /// The cells of the array, one per element.
503    #[inline]
504    fn cells(&self) -> &[TVMFFIAny] {
505        let container = self.as_container();
506        if container.size == 0 {
507            return &[];
508        }
509        // SAFETY: a non-empty array owns `size` initialized cells at `data`,
510        // and an `Array` is immutable while it is borrowed.
511        unsafe {
512            std::slice::from_raw_parts(container.data as *const TVMFFIAny, container.size as usize)
513        }
514    }
515
516    #[inline]
517    fn as_container(&self) -> &ArrayObj {
518        // SAFETY: `self.data` keeps the array object alive while it is borrowed.
519        unsafe { &*ObjectArc::as_ptr(&self.data) }
520    }
521}
522
523// -----------------------------------------------------------------------------
524// Index
525// -----------------------------------------------------------------------------
526
527/// Lends `&T` from the array's cell in place. Every cell of an `Array<T>`
528/// holds a `T` (checked when the array is built), so only a debug check runs.
529impl<T: ContainerElement + Clone + RefFromAnyUnchecked> std::ops::Index<usize> for Array<T> {
530    type Output = T;
531
532    fn index(&self, index: usize) -> &T {
533        let container = self.as_container();
534        let len = container.size as usize;
535        if index >= len {
536            panic!(
537                "Index out of bounds: the len is {} but the index is {}",
538                len, index
539            );
540        }
541        unsafe {
542            let cell = &*(container.data as *const TVMFFIAny).add(index);
543            debug_assert!(T::container_check_any_strict(cell));
544            T::ref_from_any_unchecked(cell)
545        }
546    }
547}
548
549// -----------------------------------------------------------------------------
550// Iterators
551// -----------------------------------------------------------------------------
552
553impl<T: ContainerElement + Clone + RefFromAnyUnchecked> Array<T> {
554    /// Return an iterator that borrows each element in place, without a
555    /// reference-count bump, as `array[i]` does.
556    ///
557    /// Element types stored in another representation, such as `bool` or
558    /// `i32` (held as `i64`), iterate by value instead: `for x in array`.
559    ///
560    /// ```
561    /// use tvm_ffi::Array;
562    /// let array = Array::from_vec(vec![1_i64, 2, 3]);
563    /// assert_eq!(array.iter().sum::<i64>(), 6);
564    /// ```
565    pub fn iter(&self) -> Iter<'_, T> {
566        Iter {
567            cells: self.cells().iter(),
568            _marker: std::marker::PhantomData,
569        }
570    }
571}
572
573/// An iterator that borrows the elements of an [`Array`] in place.
574pub struct Iter<'a, T> {
575    cells: std::slice::Iter<'a, TVMFFIAny>,
576    _marker: std::marker::PhantomData<&'a T>,
577}
578
579impl<'a, T: ContainerElement + RefFromAnyUnchecked> Iterator for Iter<'a, T> {
580    type Item = &'a T;
581
582    #[inline]
583    fn next(&mut self) -> Option<&'a T> {
584        self.cells.next().map(|cell| unsafe {
585            // SAFETY: every cell of an `Array<T>` holds a `T`, checked when the
586            // array is built.
587            debug_assert!(T::container_check_any_strict(cell));
588            T::ref_from_any_unchecked(cell)
589        })
590    }
591
592    #[inline]
593    fn size_hint(&self) -> (usize, Option<usize>) {
594        self.cells.size_hint()
595    }
596}
597
598impl<T: ContainerElement + RefFromAnyUnchecked> DoubleEndedIterator for Iter<'_, T> {
599    #[inline]
600    fn next_back(&mut self) -> Option<Self::Item> {
601        self.cells.next_back().map(|cell| unsafe {
602            debug_assert!(T::container_check_any_strict(cell));
603            T::ref_from_any_unchecked(cell)
604        })
605    }
606}
607
608impl<T: ContainerElement + RefFromAnyUnchecked> ExactSizeIterator for Iter<'_, T> {}
609
610impl<'a, T: ContainerElement + Clone + RefFromAnyUnchecked> IntoIterator for &'a Array<T> {
611    type Item = &'a T;
612    type IntoIter = Iter<'a, T>;
613
614    fn into_iter(self) -> Self::IntoIter {
615        self.iter()
616    }
617}
618
619/// An iterator that yields the elements of an [`Array`] by value.
620pub struct IntoIter<T> {
621    array: Array<T>,
622    index: usize,
623}
624
625impl<T: ContainerElement + Clone> Iterator for IntoIter<T> {
626    type Item = T;
627
628    #[inline]
629    fn next(&mut self) -> Option<T> {
630        let cell = self.array.cells().get(self.index)?;
631        self.index += 1;
632        // SAFETY: every cell of an `Array<T>` holds a `T`, checked when the
633        // array is built.
634        Some(unsafe {
635            debug_assert!(T::container_check_any_strict(cell));
636            T::container_copy_from_any_view_after_check(cell)
637        })
638    }
639
640    #[inline]
641    fn size_hint(&self) -> (usize, Option<usize>) {
642        let remaining = self.array.len() - self.index;
643        (remaining, Some(remaining))
644    }
645}
646
647impl<T: ContainerElement + Clone> ExactSizeIterator for IntoIter<T> {}
648
649/// Iterate by value, for every element type. Cloning an `Array` first costs one
650/// reference-count bump for the whole array.
651impl<T: ContainerElement + Clone> IntoIterator for Array<T> {
652    type Item = T;
653    type IntoIter = IntoIter<T>;
654
655    fn into_iter(self) -> Self::IntoIter {
656        IntoIter {
657            array: self,
658            index: 0,
659        }
660    }
661}
662
663impl<T: ContainerElement + Clone> FromIterator<T> for Array<T> {
664    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
665        let items: Vec<T> = iter.into_iter().collect();
666        Self::from_vec(items)
667    }
668}
669
670// -----------------------------------------------------------------------------
671// Any conversions
672// -----------------------------------------------------------------------------
673
674unsafe impl<T> AnyCompatible for Array<T>
675where
676    T: ContainerElement + Clone,
677{
678    #[inline]
679    unsafe fn is_undefined(field: *const Self) -> bool {
680        unsafe { ObjectArc::is_null(std::ptr::addr_of!((*field).data)) }
681    }
682
683    fn type_str() -> String {
684        format!("Array<{}>", T::container_type_str())
685    }
686
687    fn type_schema() -> String {
688        crate::type_traits::type_schema(
689            <ArrayObj as crate::ObjectCore>::TYPE_KEY,
690            &[T::container_type_schema()],
691        )
692    }
693
694    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
695        if data.type_index != TypeIndex::kTVMFFIArray as i32 {
696            return false;
697        }
698
699        let container = unsafe { &*(data.data_union.v_obj as *const ArrayObj) };
700        let base_ptr = container.data as *const TVMFFIAny;
701        for i in 0..container.size {
702            let elem_any = unsafe { &*base_ptr.add(i as usize) };
703            if unsafe { !T::container_check_any_strict(elem_any) } {
704                return false;
705            }
706        }
707        true
708    }
709
710    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
711        let container = unsafe { &*(data.data_union.v_obj as *const ArrayObj) };
712        let base_ptr = container.data as *const TVMFFIAny;
713        for i in 0..container.size {
714            let elem_any = unsafe { &*base_ptr.add(i as usize) };
715            if unsafe { !T::container_match_constraints(elem_any) } {
716                return false;
717            }
718        }
719        true
720    }
721
722    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
723        data.type_index = TypeIndex::kTVMFFIArray as i32;
724        data.data_union.v_obj = ObjectArc::as_ptr(Self::data(src)) as *mut TVMFFIObject;
725        data.small_str_len = 0;
726    }
727
728    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
729        data.type_index = TypeIndex::kTVMFFIArray as i32;
730        data.data_union.v_obj = ObjectArc::into_raw(Self::into_data(src)) as *mut TVMFFIObject;
731        data.small_str_len = 0;
732    }
733
734    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
735        let ptr = unsafe { data.data_union.v_obj as *const ArrayObj };
736        unsafe { crate::object::unsafe_::inc_ref(ptr as *mut TVMFFIObject) };
737        unsafe { Self::from_data(ObjectArc::from_raw(ptr)) }
738    }
739
740    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
741        let ptr = unsafe { data.data_union.v_obj as *const ArrayObj };
742        let obj = unsafe { Self::from_data(ObjectArc::from_raw(ptr)) };
743
744        data.type_index = TypeIndex::kTVMFFINone as i32;
745        data.data_union.v_int64 = 0;
746
747        obj
748    }
749
750    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
751        // Mirrors C++ `SeqTypeTraitsBase::TryCastFromAnyView`: `ffi.List` is
752        // the accepted other sequence type, and is always copied.
753        if data.type_index != TypeIndex::kTVMFFIArray as i32
754            && data.type_index != TypeIndex::kTVMFFIList as i32
755        {
756            return Err(());
757        }
758
759        // Fast path: an array whose elements all match shares the reference.
760        if unsafe { <Self as AnyCompatible>::check_any_strict(data) } {
761            return Ok(unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) });
762        }
763
764        // Slow path: convert element by element into a new array.
765        let cells = unsafe { seq_cells(data) };
766        let mut items = Vec::with_capacity(cells.len());
767        for cell in cells {
768            unsafe { items.push(T::container_try_cast_from_any_view(cell)?) };
769        }
770        Ok(Array::from_vec(items))
771    }
772}
773
774// The cell's payload word is the single object pointer of the handle.
775unsafe impl<T> crate::type_traits::RefFromAnyUnchecked for Array<T>
776where
777    T: ContainerElement + Clone,
778{
779    #[inline(always)]
780    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
781        unsafe { &*(core::ptr::addr_of!(cell.data_union) as *const Self) }
782    }
783}
784
785unsafe impl<T> crate::type_traits::DowncastRefFromAny for Array<T>
786where
787    T: ContainerElement + Clone,
788{
789    #[inline(always)]
790    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
791        unsafe { crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
792    }
793}
794
795unsafe impl<T> crate::type_traits::DowncastRefFromObject for Array<T>
796where
797    T: ContainerElement + Clone,
798{
799    #[inline(always)]
800    unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
801        unsafe { crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
802    }
803}
804
805impl<'b, T> TryFrom<&'b Any> for Array<T>
806where
807    T: ContainerElement + Clone,
808{
809    type Error = crate::error::Error;
810
811    fn try_from(value: &'b Any) -> Result<Self, Self::Error> {
812        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
813        Ok(TryFromTemp::into_value(temp))
814    }
815}
816
817impl<T> TryFrom<Any> for Array<T>
818where
819    T: ContainerElement + Clone,
820{
821    type Error = crate::error::Error;
822
823    fn try_from(value: Any) -> Result<Self, Self::Error> {
824        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
825        Ok(TryFromTemp::into_value(temp))
826    }
827}
828
829impl<'a, T> TryFrom<AnyView<'a>> for Array<T>
830where
831    T: ContainerElement + Clone,
832{
833    type Error = crate::error::Error;
834
835    fn try_from(value: AnyView<'a>) -> Result<Self, Self::Error> {
836        let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
837        Ok(TryFromTemp::into_value(temp))
838    }
839}
840
841// -----------------------------------------------------------------------------
842// Helpers
843// -----------------------------------------------------------------------------
844
845/// Move `value` into the uninitialized `cell`.
846unsafe fn write_cell<T: ContainerElement>(cell: *mut TVMFFIAny, value: T) {
847    let mut raw = TVMFFIAny::new();
848    unsafe { T::container_move_to_any(value, &mut raw) };
849    unsafe { std::ptr::write(cell, raw) };
850}