use std::borrow::Borrow;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Deref;
use crate::IntoArg;
use crate::any::TryFromTemp;
use crate::derive::Object;
use crate::extra::cold_init_lazy_lock::ColdInitLazyLock;
use crate::function::Function;
use crate::object::{Object, ObjectArc};
use crate::type_traits::{ContainerElement, TypeSubsumes};
use crate::{Any, AnyCompatible, AnyView, Error, ObjectRefCore, Result};
use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
use tvm_ffi_sys::{TVMFFIAny, TVMFFIObject};
#[inline]
pub(crate) fn element_view<T: ContainerElement>(value: &T) -> AnyView<'_> {
unsafe {
let mut data = TVMFFIAny::new();
T::container_copy_to_any_view(value, &mut data);
AnyView::from_raw_ffi_any(data)
}
}
static MISSING_OBJECT: ColdInitLazyLock<usize> = ColdInitLazyLock::new(|| {
let missing = Function::get_global("ffi.GetInvalidObject")
.and_then(|f| f.call_packed(&[]))
.expect("ffi.GetInvalidObject failed");
unsafe { missing.as_raw_ffi_any().data_union.v_obj as usize }
});
fn element_from_any<T: ContainerElement>(value: Any) -> Result<T> {
unsafe {
if T::container_check_any_strict(value.as_raw_ffi_any()) {
let mut value = std::mem::ManuallyDrop::new(value);
return Ok(T::container_move_from_any_after_check(
&mut *value.as_raw_ffi_any_mut(),
));
}
T::container_try_cast_from_any_view(value.as_raw_ffi_any()).map_err(|()| {
let message = format!(
"Cannot convert from type `{}` to `{}`",
T::container_get_mismatch_type_info(value.as_raw_ffi_any()),
T::container_type_str()
);
Error::new(crate::error::TYPE_ERROR, &message)
})
}
}
#[repr(C)]
#[derive(Object)]
#[object(type_key = "ffi.Map", unsafe type_index = TypeIndex::kTVMFFIMap)]
pub struct MapObj {
pub(crate) object: Object,
pub data: *mut core::ffi::c_void,
pub size: u64,
pub slots: u64,
}
#[repr(C)]
pub struct Map<K, V> {
data: ObjectArc<MapObj>,
_marker: PhantomData<(K, V)>,
}
unsafe impl<K: Send + Sync, V: Send + Sync> Send for Map<K, V> {}
unsafe impl<K: Send + Sync, V: Send + Sync> Sync for Map<K, V> {}
impl<K, V> Clone for Map<K, V> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
_marker: PhantomData,
}
}
}
impl<K, V> From<Map<K, V>> for crate::object::ObjectRef
where
Map<K, V>: ObjectRefCore,
{
#[inline]
fn from(value: Map<K, V>) -> Self {
crate::object::into_root_object_ref(value)
}
}
impl<K, V> TryFrom<crate::object::ObjectRef> for Map<K, V>
where
Map<K, V>: ObjectRefCore,
{
type Error = crate::error::Error;
#[inline]
fn try_from(value: crate::object::ObjectRef) -> crate::error::Result<Self> {
crate::object::root_try_into(value)
}
}
impl<K, V> TryFrom<&crate::object::ObjectRef> for Map<K, V>
where
Map<K, V>: ObjectRefCore + crate::type_traits::DowncastRefFromObject,
{
type Error = crate::error::Error;
#[inline]
fn try_from(value: &crate::object::ObjectRef) -> crate::error::Result<Self> {
crate::object::root_try_into_ref(value)
}
}
unsafe impl<K: ContainerElement, V: ContainerElement> ObjectRefCore for Map<K, V> {
type ContainerType = MapObj;
fn data(this: &Self) -> &ObjectArc<MapObj> {
&this.data
}
fn into_data(this: Self) -> ObjectArc<MapObj> {
this.data
}
unsafe fn from_data(data: ObjectArc<MapObj>) -> Self {
Self {
data,
_marker: PhantomData,
}
}
}
impl<K, V> Deref for Map<K, V> {
type Target = MapObj;
#[inline]
fn deref(&self) -> &MapObj {
&self.data
}
}
impl<K, V> Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
pub fn new() -> Self {
Self::from_pairs(&[]).expect("ffi.Map() failed to construct an empty map")
}
fn from_pairs(pairs: &[(K, V)]) -> Result<Self> {
let mut args: Vec<AnyView<'_>> = Vec::with_capacity(pairs.len() * 2);
for (k, v) in pairs {
args.push(element_view(k));
args.push(element_view(v));
}
let result = crate::cached_global_func!("ffi.Map").call_packed(&args)?;
Self::try_from(result)
}
pub fn len(&self) -> usize {
self.size as usize
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn try_contains_key(&self, key: &K) -> Result<bool> {
let result = crate::cached_global_func!("ffi.MapCount")
.call_packed(&[AnyView::from(self), element_view(key)])?;
Ok(i64::try_from(result)? != 0)
}
#[inline]
fn debug_assert_key_type(&self) {
#[cfg(debug_assertions)]
{
if !self.is_empty() {
let functor = self.iter_functor();
let first_key = functor
.call_packed(&[AnyView::from(&0i64)])
.expect("map iterator: reading current key failed");
assert!(
unsafe { K::container_check_any_strict(first_key.as_raw_ffi_any()) },
"Map lookup: key type `{}` does not match the map's stored key type",
std::any::type_name::<K>(),
);
}
}
}
pub fn contains_key(&self, key: impl IntoArg<K>) -> Result<bool> {
let present = self.try_contains_key(key.into_arg().borrow())?;
if !present {
self.debug_assert_key_type();
}
Ok(present)
}
pub fn get(&self, key: impl IntoArg<K>) -> Result<Option<V>> {
let key = key.into_arg();
let result = crate::cached_global_func!("ffi.MapGetItemOrMissing")
.call_packed(&[AnyView::from(self), element_view(key.borrow())])?;
let raw = result.as_raw_ffi_any();
if raw.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32
&& unsafe { raw.data_union.v_obj } as usize == *MISSING_OBJECT
{
self.debug_assert_key_type();
return Ok(None);
}
let value = element_from_any(result)?;
Ok(Some(value))
}
pub fn iter(&self) -> Iter<K, V> {
Iter(self.make_iter(|f| (iter_read::<K>(f, 0, "key"), iter_read::<V>(f, 1, "value"))))
}
pub fn keys(&self) -> Keys<K> {
Keys(self.make_iter(|f| iter_read::<K>(f, 0, "key")))
}
pub fn values(&self) -> Values<V> {
Values(self.make_iter(|f| iter_read::<V>(f, 1, "value")))
}
fn make_iter<T>(&self, read: fn(&Function) -> T) -> MapIter<T> {
let remaining = self.len();
MapIter {
functor: (remaining != 0).then(|| self.iter_functor()),
remaining,
_keepalive: self.data.clone(),
read,
}
}
fn iter_functor(&self) -> Function {
let result = crate::cached_global_func!("ffi.MapForwardIterFunctor")
.call_packed(&[AnyView::from(self)])
.expect("ffi.MapForwardIterFunctor call failed");
Function::try_from(result).expect("ffi.MapForwardIterFunctor returned a non-function")
}
fn try_raw_entries(&self) -> Result<Vec<(Any, Any)>> {
forward_entries(
crate::cached_global_func!("ffi.MapForwardIterFunctor"),
AnyView::from(self),
self.len(),
)
}
fn from_raw_entries(entries: Vec<(Any, Any)>) -> Result<Self> {
let mut pairs = Vec::with_capacity(entries.len());
for (k, v) in entries {
pairs.push((element_from_any::<K>(k)?, element_from_any::<V>(v)?));
}
Self::from_pairs(&pairs)
}
}
fn forward_entries(
iter_functor: &Function,
container: AnyView,
len: usize,
) -> Result<Vec<(Any, Any)>> {
let mut entries = Vec::with_capacity(len);
let mut remaining = len;
if remaining == 0 {
return Ok(entries);
}
let functor = iter_functor
.call_packed(&[container])
.and_then(Function::try_from)?;
loop {
let k = functor.call_packed(&[AnyView::from(&0i64)])?;
let v = functor.call_packed(&[AnyView::from(&1i64)])?;
entries.push((k, v));
remaining -= 1;
if remaining == 0 {
return Ok(entries);
}
functor.call_packed(&[AnyView::from(&2i64)])?;
}
}
impl<K, V> Default for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
fn default() -> Self {
Self::new()
}
}
impl<K, V> Debug for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn short(name: &str) -> &str {
name.split("::").last().unwrap_or(name)
}
write!(
f,
"Map<{}, {}>[{}]",
short(std::any::type_name::<K>()),
short(std::any::type_name::<V>()),
self.len()
)
}
}
impl<K: ContainerElement, V: ContainerElement> std::fmt::Display for Map<K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&AnyView::from_object(&**ObjectRefCore::data(self)), f)
}
}
impl<K, V> FromIterator<(K, V)> for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let pairs: Vec<(K, V)> = iter.into_iter().collect();
Self::from_pairs(&pairs).expect("ffi.Map() failed to construct a map")
}
}
impl<K: ContainerElement, V: ContainerElement, const N: usize> From<[(K, V); N]> for Map<K, V> {
fn from(pairs: [(K, V); N]) -> Self {
Self::from_pairs(&pairs).expect("ffi.Map() failed to construct a map")
}
}
impl<K, V> From<&Map<K, V>> for Map<K, V> {
#[inline]
fn from(value: &Map<K, V>) -> Self {
value.clone()
}
}
impl<K, V> Map<K, V> {
#[inline(always)]
pub fn upcast<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(self) -> Map<KU, VU> {
Map {
data: self.data,
_marker: PhantomData,
}
}
#[inline(always)]
pub fn upcast_ref<KU: TypeSubsumes<K>, VU: TypeSubsumes<V>>(&self) -> &Map<KU, VU> {
unsafe { &*(self as *const Self as *const Map<KU, VU>) }
}
}
impl<K, V, KU: TypeSubsumes<K>, VU: TypeSubsumes<V>> IntoArg<Map<KU, VU>> for Map<K, V> {
type Output = Map<KU, VU>;
#[inline(always)]
fn into_arg(self) -> Map<KU, VU> {
self.upcast()
}
#[inline(always)]
fn into_owned(self) -> Map<KU, VU> {
self.upcast()
}
}
impl<'a, K, V, KU: TypeSubsumes<K> + 'a, VU: TypeSubsumes<V> + 'a> IntoArg<Map<KU, VU>>
for &'a Map<K, V>
{
type Output = &'a Map<KU, VU>;
#[inline(always)]
fn into_arg(self) -> &'a Map<KU, VU> {
self.upcast_ref()
}
#[inline(always)]
fn into_owned(self) -> Map<KU, VU> {
self.upcast_ref().clone()
}
}
fn iter_read<T: ContainerElement>(functor: &Function, command: i64, kind: &str) -> T {
let any = functor
.call_packed(&[AnyView::from(&command)])
.expect("map iterator: reading current element failed");
element_from_any(any)
.unwrap_or_else(|_| panic!("map iterator: {kind} does not match the map's {kind} type"))
}
fn iter_advance(functor: &Function, remaining: &mut usize) {
debug_assert!(
*remaining > 0,
"iter_advance called with no remaining entries"
);
*remaining -= 1;
if *remaining > 0 {
functor
.call_packed(&[AnyView::from(&2i64)])
.expect("map iterator: advancing failed");
}
}
struct MapIter<T> {
functor: Option<Function>,
remaining: usize,
_keepalive: ObjectArc<MapObj>,
read: fn(&Function) -> T,
}
impl<T> Iterator for MapIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.remaining == 0 {
return None;
}
let functor = self
.functor
.as_ref()
.expect("non-empty map iterator has a functor");
let item = (self.read)(functor);
iter_advance(functor, &mut self.remaining);
Some(item)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl<T> ExactSizeIterator for MapIter<T> {}
macro_rules! map_iterator {
($(#[$doc:meta])* $name:ident<$($param:ident),+>, $item:ty) => {
$(#[$doc])*
pub struct $name<$($param),+>(MapIter<$item>);
impl<$($param),+> Iterator for $name<$($param),+> {
type Item = $item;
#[inline]
fn next(&mut self) -> Option<$item> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<$($param),+> ExactSizeIterator for $name<$($param),+> {}
};
}
map_iterator!(
Iter<K, V>, (K, V)
);
map_iterator!(
Keys<K>, K
);
map_iterator!(
Values<V>, V
);
impl<K, V> IntoIterator for &Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
type Item = (K, V);
type IntoIter = Iter<K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
unsafe impl<K, V> AnyCompatible for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
#[inline]
unsafe fn is_undefined(field: *const Self) -> bool {
unsafe { ObjectArc::is_null(std::ptr::addr_of!((*field).data)) }
}
fn type_str() -> String {
format!(
"Map<{}, {}>",
K::container_type_str(),
V::container_type_str()
)
}
fn type_schema() -> String {
crate::type_traits::type_schema(
<MapObj as crate::ObjectCore>::TYPE_KEY,
&[K::container_type_schema(), V::container_type_schema()],
)
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
if data.type_index != TypeIndex::kTVMFFIMap as i32 {
return false;
}
let map = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
match map.try_raw_entries() {
Ok(entries) => entries.iter().all(|(k, v)| unsafe {
K::container_check_any_strict(k.as_raw_ffi_any())
&& V::container_check_any_strict(v.as_raw_ffi_any())
}),
Err(_) => false,
}
}
unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
let map = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
match map.try_raw_entries() {
Ok(entries) => entries.iter().all(|(k, v)| unsafe {
K::container_match_constraints(k.as_raw_ffi_any())
&& V::container_match_constraints(v.as_raw_ffi_any())
}),
Err(_) => false,
}
}
unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
data.type_index = TypeIndex::kTVMFFIMap 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::kTVMFFIMap 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 MapObj };
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 MapObj };
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::kTVMFFIDict as i32 {
let len = unsafe { (*(data.data_union.v_obj as *const MapObj)).size as usize };
let entries = unsafe {
forward_entries(
crate::cached_global_func!("ffi.DictForwardIterFunctor"),
AnyView::from_raw_ffi_any(*data),
len,
)
.map_err(|_| ())?
};
return Self::from_raw_entries(entries).map_err(|_| ());
}
if data.type_index != TypeIndex::kTVMFFIMap 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 src = unsafe { <Self as AnyCompatible>::copy_from_any_view_after_check(data) };
let entries = src.try_raw_entries().map_err(|_| ())?;
Self::from_raw_entries(entries).map_err(|_| ())
}
}
unsafe impl<K, V> crate::type_traits::RefFromAnyUnchecked for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
#[inline(always)]
unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
unsafe { &*(core::ptr::addr_of!(cell.data_union) as *const Self) }
}
}
unsafe impl<K, V> crate::type_traits::DowncastRefFromAny for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
#[inline(always)]
unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
unsafe { crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
}
}
unsafe impl<K, V> crate::type_traits::DowncastRefFromObject for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
#[inline(always)]
unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
unsafe { crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
}
}
impl<'b, K, V> TryFrom<&'b Any> for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
type Error = Error;
fn try_from(value: &'b Any) -> Result<Self> {
let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
Ok(TryFromTemp::into_value(temp))
}
}
impl<K, V> TryFrom<Any> for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
type Error = Error;
fn try_from(value: Any) -> Result<Self> {
let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
Ok(TryFromTemp::into_value(temp))
}
}
impl<'a, K, V> TryFrom<AnyView<'a>> for Map<K, V>
where
K: ContainerElement,
V: ContainerElement,
{
type Error = Error;
fn try_from(value: AnyView<'a>) -> Result<Self> {
let temp: TryFromTemp<Self> = TryFromTemp::try_from(value)?;
Ok(TryFromTemp::into_value(temp))
}
}