use ::bevy_reflect::PartialReflect;
use bevy_mod_scripting_display::{
DebugWithTypeInfo, DebugWithTypeInfoBuilder, DisplayWithTypeInfo,
};
use bevy_mod_scripting_world::{ExternalValue, SharedClaims, WorldAccessRange, WorldGuard};
use std::{
cell::UnsafeCell,
cmp::Ordering,
fmt::{Display, Formatter},
hash::Hasher,
sync::Arc,
};
#[derive(Clone)]
pub struct ReflectAllocationId {
value: Arc<dyn AllocatedValue>,
}
trait AllocatedValue: ExternalValue {
fn get_ptr(&self) -> *mut dyn PartialReflect;
}
struct Inline<T> {
claims: SharedClaims,
value: UnsafeCell<T>,
}
unsafe impl<T: Send> Sync for Inline<T> {}
impl<T: Send + 'static> ExternalValue for Inline<T> {
fn claims(&self) -> &SharedClaims {
&self.claims
}
}
impl<T: PartialReflect> AllocatedValue for Inline<T> {
fn get_ptr(&self) -> *mut dyn PartialReflect {
self.value.get()
}
}
struct Boxed {
claims: SharedClaims,
value: Box<UnsafeCell<dyn PartialReflect>>,
}
unsafe impl Sync for Boxed {}
impl ExternalValue for Boxed {
fn claims(&self) -> &SharedClaims {
&self.claims
}
}
impl AllocatedValue for Boxed {
fn get_ptr(&self) -> *mut dyn PartialReflect {
UnsafeCell::get(&*self.value)
}
}
impl ReflectAllocationId {
pub fn new<T: PartialReflect>(value: T) -> Self {
Self {
value: Arc::new(Inline {
claims: SharedClaims::default(),
value: UnsafeCell::new(value),
}),
}
}
pub fn new_boxed(value: Box<dyn PartialReflect>) -> Self {
let value: Box<UnsafeCell<dyn PartialReflect>> = unsafe { std::mem::transmute(value) };
Self {
value: Arc::new(Boxed {
claims: SharedClaims::default(),
value,
}),
}
}
pub fn id(&self) -> usize {
Arc::as_ptr(&self.value) as *const () as usize
}
pub fn get_ptr(&self) -> *mut dyn PartialReflect {
self.value.get_ptr()
}
pub fn strong_count(&self) -> usize {
Arc::strong_count(&self.value)
}
}
impl DebugWithTypeInfo for ReflectAllocationId {
fn to_string_with_type_info(
&self,
f: &mut std::fmt::Formatter<'_>,
type_info_provider: Option<&WorldGuard>,
) -> std::fmt::Result {
f.debug_tuple_with_type_info("ReflectAllocationId", type_info_provider)
.field(&self.id())
.finish()
}
}
impl From<&ReflectAllocationId> for WorldAccessRange {
fn from(val: &ReflectAllocationId) -> Self {
WorldAccessRange::External(val.value.clone())
}
}
impl DisplayWithTypeInfo for ReflectAllocationId {
fn display_with_type_info(
&self,
f: &mut std::fmt::Formatter<'_>,
_type_info_provider: Option<&WorldGuard>,
) -> std::fmt::Result {
write!(f, "{}", self.id())
}
}
impl Display for ReflectAllocationId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.id())
}
}
impl std::hash::Hash for ReflectAllocationId {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
}
impl PartialEq for ReflectAllocationId {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl Eq for ReflectAllocationId {}
impl PartialOrd for ReflectAllocationId {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ReflectAllocationId {
fn cmp(&self, other: &Self) -> Ordering {
self.id().cmp(&other.id())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn access_keys_and_clones_share_the_allocation() {
let id = ReflectAllocationId::new(1usize);
let key = WorldAccessRange::from(&id);
let clone = id.clone();
assert_eq!(id.strong_count(), 3);
let WorldAccessRange::External(owner) = &key else {
panic!("allocations are external")
};
assert_eq!(bevy_mod_scripting_world::external_access_id(owner), id.id());
assert_eq!(clone.id(), id.id());
drop(key);
drop(clone);
assert_eq!(id.strong_count(), 1);
}
#[test]
fn inline_and_boxed_values_are_readable() {
let inline = ReflectAllocationId::new(3usize);
let boxed = ReflectAllocationId::new_boxed(Box::new(String::from("string")));
unsafe {
assert!((*inline.get_ptr()).reflect_partial_eq(&3usize).unwrap());
assert!(
(*boxed.get_ptr())
.reflect_partial_eq(&String::from("string"))
.unwrap()
);
}
assert_ne!(inline.id(), boxed.id());
}
}