1use 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#[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 pub data: *mut core::ffi::c_void,
43 pub size: i64,
45 pub capacity: i64,
47 pub data_deleter: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
49}
50
51unsafe impl ObjectCoreWithExtraItems for ArrayObj {
54 type ExtraItem = TVMFFIAny;
55 fn extra_items_count(this: &Self) -> usize {
56 this.capacity as usize
57 }
58}
59
60impl 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 drop(unsafe { Any::from_raw_ffi_any(*cells.add(i)) });
68 }
69 }
70}
71
72#[repr(C)]
107#[derive(Clone)]
108pub struct Array<T> {
109 data: ObjectArc<ArrayObj>,
110 _marker: PhantomData<T>,
111}
112
113unsafe 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
126impl<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
157impl<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
189impl<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
197impl<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 #[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 #[inline(always)]
240 pub fn upcast_ref<U: TypeSubsumes<T>>(&self) -> &Array<U> {
241 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 pub fn new() -> Self {
275 Self::from_vec(Vec::new())
276 }
277
278 pub fn from_vec(items: Vec<T>) -> Self {
297 let capacity = items.len();
298 Self::new_with_capacity(items, capacity)
299 }
300
301 pub fn push(&mut self, value: T) {
305 let size = self.len();
306 let container = self.make_mut(size + 1);
307 unsafe { write_cell((container.data as *mut TVMFFIAny).add(size), value) };
309 container.size += 1;
310 }
311
312 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 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 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 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 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 container.size = len as i64;
368 let cells = container.data as *const TVMFFIAny;
369 for i in len..size {
370 drop(unsafe { Any::from_raw_ffi_any(*cells.add(i)) });
372 }
373 }
374
375 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 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 pub fn len(&self) -> usize {
404 self.data.size as usize
405 }
406
407 pub fn is_empty(&self) -> bool {
413 self.len() == 0
414 }
415
416 pub fn get(&self, index: usize) -> Option<T> {
420 let cell = self.cells().get(index)?;
421 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 fn new_with_capacity(items: Vec<T>, capacity: usize) -> Self {
431 let size = items.len();
432
433 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 unsafe { Self::from_data(arc) }
456 }
457
458 fn make_mut(&mut self, capacity: usize) -> &mut ArrayObj {
461 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 unsafe { &mut *ObjectArc::as_mut_ptr(&mut self.data) }
475 }
476
477 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 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 #[inline]
504 fn cells(&self) -> &[TVMFFIAny] {
505 let container = self.as_container();
506 if container.size == 0 {
507 return &[];
508 }
509 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 unsafe { &*ObjectArc::as_ptr(&self.data) }
520 }
521}
522
523impl<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
549impl<T: ContainerElement + Clone + RefFromAnyUnchecked> Array<T> {
554 pub fn iter(&self) -> Iter<'_, T> {
566 Iter {
567 cells: self.cells().iter(),
568 _marker: std::marker::PhantomData,
569 }
570 }
571}
572
573pub 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 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
619pub 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 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
649impl<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
670unsafe 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 if data.type_index != TypeIndex::kTVMFFIArray as i32
754 && data.type_index != TypeIndex::kTVMFFIList as i32
755 {
756 return Err(());
757 }
758
759 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 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
774unsafe 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
841unsafe 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}