use std::fmt::Debug;
use std::marker::PhantomData;
use crate::IntoArg;
use crate::any::TryFromTemp;
use crate::collections::list::seq_cells;
use crate::derive::Object;
use crate::object::ObjectCoreWithExtraItems;
use crate::object::{Object, ObjectArc};
use crate::type_traits::{ContainerElement, RefFromAnyUnchecked, TypeSubsumes};
use crate::{Any, AnyCompatible, AnyView, ObjectRefCore};
use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};
#[repr(C)]
#[derive(Object)]
#[object(type_key = "ffi.Array", unsafe type_index = TypeIndex::kTVMFFIArray)]
pub struct ArrayObj {
pub(crate) object: Object,
pub data: *mut core::ffi::c_void,
pub size: i64,
pub capacity: i64,
pub data_deleter: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
}
unsafe impl ObjectCoreWithExtraItems for ArrayObj {
type ExtraItem = TVMFFIAny;
fn extra_items_count(this: &Self) -> usize {
this.capacity as usize
}
}
impl Drop for ArrayObj {
fn drop(&mut self) {
let cells = self.data as *const TVMFFIAny;
for i in 0..self.size as usize {
drop(unsafe { Any::from_raw_ffi_any(*cells.add(i)) });
}
}
}
#[repr(C)]
#[derive(Clone)]
pub struct Array<T> {
data: ObjectArc<ArrayObj>,
_marker: PhantomData<T>,
}
unsafe impl<T: Send + Sync> Send for Array<T> {}
unsafe impl<T: Send + Sync> Sync for Array<T> {}
impl<T: ContainerElement + Clone> Debug for Array<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, "Array<{}>[{}]", short_name, self.len())
}
}
impl<T: ContainerElement + Clone> std::fmt::Display for Array<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 + Clone> Default for Array<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: ContainerElement + Clone> From<Vec<T>> for Array<T> {
fn from(items: Vec<T>) -> Self {
Self::from_vec(items)
}
}
impl<T: ContainerElement + Clone, const N: usize> From<[T; N]> for Array<T> {
fn from(items: [T; N]) -> Self {
Self::from_vec(items.into())
}
}
impl<T: ContainerElement + Clone> From<&[T]> for Array<T> {
fn from(items: &[T]) -> Self {
Self::from_vec(items.to_vec())
}
}
impl<T: ContainerElement + Clone> From<&Array<T>> for Array<T> {
#[inline]
fn from(value: &Array<T>) -> Self {
value.clone()
}
}
impl<T, U: TypeSubsumes<T>> IntoArg<Array<U>> for Array<T> {
type Output = Array<U>;
#[inline(always)]
fn into_arg(self) -> Array<U> {
self.upcast()
}
#[inline(always)]
fn into_owned(self) -> Array<U> {
self.upcast()
}
}
impl<'a, T, U: TypeSubsumes<T> + ContainerElement + Clone + 'a> IntoArg<Array<U>> for &'a Array<T> {
type Output = &'a Array<U>;
#[inline(always)]
fn into_arg(self) -> &'a Array<U> {
self.upcast_ref()
}
#[inline(always)]
fn into_owned(self) -> Array<U> {
self.upcast_ref().clone()
}
}
impl<T: ContainerElement + Clone> From<Array<T>> for crate::object::ObjectRef {
#[inline]
fn from(value: Array<T>) -> Self {
crate::object::into_root_object_ref(value)
}
}
impl<T: ContainerElement + Clone> TryFrom<crate::object::ObjectRef> for Array<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 + Clone> TryFrom<&crate::object::ObjectRef> for Array<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)
}
}
impl<T> Array<T> {
#[inline(always)]
pub fn upcast<U: TypeSubsumes<T>>(self) -> Array<U> {
Array {
data: self.data,
_marker: PhantomData,
}
}
#[inline(always)]
pub fn upcast_ref<U: TypeSubsumes<T>>(&self) -> &Array<U> {
unsafe { &*(self as *const Self as *const Array<U>) }
}
}
unsafe impl<T: ContainerElement + Clone> ObjectRefCore for Array<T> {
type ContainerType = ArrayObj;
fn data(this: &Self) -> &ObjectArc<Self::ContainerType> {
&this.data
}
fn into_data(this: Self) -> ObjectArc<Self::ContainerType> {
this.data
}
unsafe fn from_data(data: ObjectArc<Self::ContainerType>) -> Self {
Self {
data,
_marker: PhantomData,
}
}
}
impl<T: ContainerElement + Clone> Array<T> {
pub fn new() -> Self {
Self::from_vec(Vec::new())
}
pub fn from_vec(items: Vec<T>) -> Self {
let capacity = items.len();
Self::new_with_capacity(items, capacity)
}
pub fn push(&mut self, value: T) {
let size = self.len();
let container = self.make_mut(size + 1);
unsafe { write_cell((container.data as *mut TVMFFIAny).add(size), value) };
container.size += 1;
}
pub fn insert(&mut self, index: usize, value: T) {
let size = self.len();
if index > size {
panic!("insertion index (is {index}) should be <= len (is {size})");
}
let container = self.make_mut(size + 1);
unsafe {
let cell = (container.data as *mut TVMFFIAny).add(index);
std::ptr::copy(cell, cell.add(1), size - index);
write_cell(cell, value);
}
container.size += 1;
}
pub fn pop(&mut self) -> Option<T> {
let size = self.len();
if size == 0 {
return None;
}
let container = self.make_mut(size);
container.size -= 1;
unsafe {
let mut cell = std::ptr::read((container.data as *const TVMFFIAny).add(size - 1));
debug_assert!(T::container_check_any_strict(&cell));
Some(T::container_move_from_any_after_check(&mut cell))
}
}
pub fn truncate(&mut self, len: usize) {
let size = self.len();
if len >= size {
return;
}
let container = self.make_mut(size);
container.size = len as i64;
let cells = container.data as *const TVMFFIAny;
for i in len..size {
drop(unsafe { Any::from_raw_ffi_any(*cells.add(i)) });
}
}
pub fn set(&mut self, index: usize, value: T) {
let size = self.len();
if index >= size {
panic!("Index out of bounds: the len is {size} but the index is {index}");
}
let container = self.make_mut(size);
unsafe {
let cell = (container.data as *mut TVMFFIAny).add(index);
let old = Any::from_raw_ffi_any(std::ptr::read(cell));
write_cell(cell, value);
drop(old);
}
}
pub fn len(&self) -> usize {
self.data.size as usize
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, index: usize) -> Option<T> {
let cell = self.cells().get(index)?;
Some(unsafe {
debug_assert!(T::container_check_any_strict(cell));
T::container_copy_from_any_view_after_check(cell)
})
}
fn new_with_capacity(items: Vec<T>, capacity: usize) -> Self {
let size = items.len();
let mut arc = unsafe {
ObjectArc::<ArrayObj>::new_with_extra_items(ArrayObj {
object: Object::new(),
data: core::ptr::null_mut(),
size: size as i64,
capacity: capacity as i64,
data_deleter: None,
})
};
unsafe {
let container = ObjectArc::as_mut_ptr(&mut arc);
let base_ptr = ArrayObj::extra_items_ptr(container);
(*container).data = base_ptr as *mut _;
for (i, item) in items.into_iter().enumerate() {
write_cell(base_ptr.add(i), item);
}
}
unsafe { Self::from_data(arc) }
}
fn make_mut(&mut self, capacity: usize) -> &mut ArrayObj {
let unique = ObjectArc::is_unique(&self.data);
let current = self.data.capacity as usize;
if !unique || capacity > current {
let capacity = if capacity > current {
(current * 2).max(capacity)
} else {
current
};
self.copy_to_new_buffer(capacity, unique);
}
unsafe { &mut *ObjectArc::as_mut_ptr(&mut self.data) }
}
fn copy_to_new_buffer(&mut self, capacity: usize, unique: bool) {
let size = self.len();
let mut grown = Self::new_with_capacity(Vec::new(), capacity);
let source = self.as_container().data as *const TVMFFIAny;
unsafe {
let target = ObjectArc::as_mut_ptr(&mut grown.data);
let cells = (*target).data as *mut TVMFFIAny;
if unique {
std::ptr::copy_nonoverlapping(source, cells, size);
(*ObjectArc::as_mut_ptr(&mut self.data)).size = 0;
} else {
for i in 0..size {
let copy = Any::from(AnyView::from_raw_ffi_any(*source.add(i)));
std::ptr::write(cells.add(i), Any::into_raw_ffi_any(copy));
}
}
(*target).size = size as i64;
}
*self = grown;
}
#[inline]
fn cells(&self) -> &[TVMFFIAny] {
let container = self.as_container();
if container.size == 0 {
return &[];
}
unsafe {
std::slice::from_raw_parts(container.data as *const TVMFFIAny, container.size as usize)
}
}
#[inline]
fn as_container(&self) -> &ArrayObj {
unsafe { &*ObjectArc::as_ptr(&self.data) }
}
}
impl<T: ContainerElement + Clone + RefFromAnyUnchecked> std::ops::Index<usize> for Array<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
let container = self.as_container();
let len = container.size as usize;
if index >= len {
panic!(
"Index out of bounds: the len is {} but the index is {}",
len, index
);
}
unsafe {
let cell = &*(container.data as *const TVMFFIAny).add(index);
debug_assert!(T::container_check_any_strict(cell));
T::ref_from_any_unchecked(cell)
}
}
}
impl<T: ContainerElement + Clone + RefFromAnyUnchecked> Array<T> {
pub fn iter(&self) -> Iter<'_, T> {
Iter {
cells: self.cells().iter(),
_marker: std::marker::PhantomData,
}
}
}
pub struct Iter<'a, T> {
cells: std::slice::Iter<'a, TVMFFIAny>,
_marker: std::marker::PhantomData<&'a T>,
}
impl<'a, T: ContainerElement + RefFromAnyUnchecked> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
self.cells.next().map(|cell| unsafe {
debug_assert!(T::container_check_any_strict(cell));
T::ref_from_any_unchecked(cell)
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.cells.size_hint()
}
}
impl<T: ContainerElement + RefFromAnyUnchecked> DoubleEndedIterator for Iter<'_, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.cells.next_back().map(|cell| unsafe {
debug_assert!(T::container_check_any_strict(cell));
T::ref_from_any_unchecked(cell)
})
}
}
impl<T: ContainerElement + RefFromAnyUnchecked> ExactSizeIterator for Iter<'_, T> {}
impl<'a, T: ContainerElement + Clone + RefFromAnyUnchecked> IntoIterator for &'a Array<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
pub struct IntoIter<T> {
array: Array<T>,
index: usize,
}
impl<T: ContainerElement + Clone> Iterator for IntoIter<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
let cell = self.array.cells().get(self.index)?;
self.index += 1;
Some(unsafe {
debug_assert!(T::container_check_any_strict(cell));
T::container_copy_from_any_view_after_check(cell)
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.array.len() - self.index;
(remaining, Some(remaining))
}
}
impl<T: ContainerElement + Clone> ExactSizeIterator for IntoIter<T> {}
impl<T: ContainerElement + Clone> IntoIterator for Array<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
array: self,
index: 0,
}
}
}
impl<T: ContainerElement + Clone> FromIterator<T> for Array<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let items: Vec<T> = iter.into_iter().collect();
Self::from_vec(items)
}
}
unsafe impl<T> AnyCompatible for Array<T>
where
T: ContainerElement + Clone,
{
#[inline]
unsafe fn is_undefined(field: *const Self) -> bool {
unsafe { ObjectArc::is_null(std::ptr::addr_of!((*field).data)) }
}
fn type_str() -> String {
format!("Array<{}>", T::container_type_str())
}
fn type_schema() -> String {
crate::type_traits::type_schema(
<ArrayObj as crate::ObjectCore>::TYPE_KEY,
&[T::container_type_schema()],
)
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
if data.type_index != TypeIndex::kTVMFFIArray as i32 {
return false;
}
let container = unsafe { &*(data.data_union.v_obj as *const ArrayObj) };
let base_ptr = container.data as *const TVMFFIAny;
for i in 0..container.size {
let elem_any = unsafe { &*base_ptr.add(i as usize) };
if unsafe { !T::container_check_any_strict(elem_any) } {
return false;
}
}
true
}
unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
let container = unsafe { &*(data.data_union.v_obj as *const ArrayObj) };
let base_ptr = container.data as *const TVMFFIAny;
for i in 0..container.size {
let elem_any = unsafe { &*base_ptr.add(i as usize) };
if unsafe { !T::container_match_constraints(elem_any) } {
return false;
}
}
true
}
unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
data.type_index = TypeIndex::kTVMFFIArray 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::kTVMFFIArray 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 ArrayObj };
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 ArrayObj };
let obj = unsafe { Self::from_data(ObjectArc::from_raw(ptr)) };
data.type_index = TypeIndex::kTVMFFINone as i32;
data.data_union.v_int64 = 0;
obj
}
unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
if data.type_index != TypeIndex::kTVMFFIArray as i32
&& data.type_index != TypeIndex::kTVMFFIList as i32
{
return Err(());
}
if unsafe { <Self as AnyCompatible>::check_any_strict(data) } {
return Ok(unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) });
}
let cells = unsafe { seq_cells(data) };
let mut items = Vec::with_capacity(cells.len());
for cell in cells {
unsafe { items.push(T::container_try_cast_from_any_view(cell)?) };
}
Ok(Array::from_vec(items))
}
}
unsafe impl<T> crate::type_traits::RefFromAnyUnchecked for Array<T>
where
T: ContainerElement + Clone,
{
#[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 Array<T>
where
T: ContainerElement + Clone,
{
#[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 Array<T>
where
T: ContainerElement + Clone,
{
#[inline(always)]
unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
unsafe { crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
}
}
impl<'b, T> TryFrom<&'b Any> for Array<T>
where
T: ContainerElement + Clone,
{
type Error = crate::error::Error;
fn try_from(value: &'b Any) -> Result<Self, Self::Error> {
let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
Ok(TryFromTemp::into_value(temp))
}
}
impl<T> TryFrom<Any> for Array<T>
where
T: ContainerElement + Clone,
{
type Error = crate::error::Error;
fn try_from(value: Any) -> Result<Self, Self::Error> {
let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
Ok(TryFromTemp::into_value(temp))
}
}
impl<'a, T> TryFrom<AnyView<'a>> for Array<T>
where
T: ContainerElement + Clone,
{
type Error = crate::error::Error;
fn try_from(value: AnyView<'a>) -> Result<Self, Self::Error> {
let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
Ok(TryFromTemp::into_value(temp))
}
}
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 { std::ptr::write(cell, raw) };
}