Skip to main content

azul_core/
refany.rs

1//! Type-erased, reference-counted smart pointer with runtime borrow checking.
2//!
3//! # Safety
4//!
5//! This module provides `RefAny`, a type-erased container similar to `Arc<RefCell<dyn Any>>`,
6//! but designed for FFI compatibility and cross-language interoperability.
7//!
8//! ## Memory Safety Guarantees
9//!
10//! 1. **Proper Alignment**: Fixed in commit addressing Miri UB - memory is allocated with correct
11//!    alignment for the stored type using `Layout::from_size_align()`.
12//!
13//! 2. **Atomic Reference Counting**: All reference counts use `AtomicUsize` with `SeqCst` ordering,
14//!    ensuring thread-safe access and preventing use-after-free.
15//!
16//! 3. **Runtime Type Safety**: Type IDs are checked before downcasting, preventing invalid pointer
17//!    casts that would cause undefined behavior.
18//!
19//! 4. **Runtime Borrow Checking**: Shared and mutable borrows are tracked at runtime, enforcing
20//!    Rust's borrowing rules dynamically (similar to `RefCell`).
21//!
22//! ## Thread Safety
23//!
24//! - `RefAny` is `Send`: Can be transferred between threads (data is heap-allocated)
25//! - `RefAny` is `Sync`: Can be shared between threads (atomic operations + `&mut self` for
26//!   borrows)
27//!
28//! The `SeqCst` (Sequentially Consistent) memory ordering provides the strongest guarantees:
29//! all atomic operations appear in a single global order visible to all threads, preventing
30//! race conditions where one thread doesn't see another's reference count updates.
31
32use alloc::boxed::Box;
33use alloc::string::String;
34use core::{
35    alloc::Layout,
36    ffi::c_void,
37    fmt,
38    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
39};
40
41use azul_css::AzString;
42
43/// C-compatible destructor function type for `RefAny`.
44/// Called when the last reference to a `RefAny` is dropped.
45pub type RefAnyDestructorType = extern "C" fn(*mut c_void);
46
47// NOTE: JSON serialization/deserialization callback types are defined in azul_layout::json
48// The actual types are:
49//   RefAnySerializeFnType = extern "C" fn(RefAny) -> Json
50//   RefAnyDeserializeFnType = extern "C" fn(Json) -> ResultRefAnyString
51// In azul_core, we only store function pointers as usize (0 = not set).
52
53/// Internal reference counting metadata for `RefAny`.
54///
55/// This struct tracks:
56///
57/// - How many `RefAny` clones exist (`num_copies`)
58/// - How many shared borrows are active (`num_refs`)
59/// - How many mutable borrows are active (`num_mutable_refs`)
60/// - Memory layout information for correct deallocation
61/// - Type information for runtime type checking
62///
63/// # Thread Safety
64///
65/// All counters are `AtomicUsize` with `SeqCst` ordering, making them safe to access
66/// from multiple threads simultaneously. The strong ordering ensures no thread can
67/// observe inconsistent states (e.g., both seeing count=1 during final drop).
68#[derive(Debug)]
69#[repr(C)]
70// `_internal_*` are C-ABI field names exposed in api.json; the `_` prefix is the
71// intentional "internal" convention and cannot be renamed without breaking the ABI.
72#[allow(clippy::pub_underscore_fields)]
73pub struct RefCountInner {
74    /// Type-erased pointer to heap-allocated data.
75    ///
76    /// SAFETY: Must be properly aligned for the stored type (guaranteed by
77    /// `Layout::from_size_align` in `new_c`). Never null for non-ZST types.
78    ///
79    /// This pointer is shared by all `RefAny` clones, so `replace_contents`
80    /// updates are visible to all clones.
81    pub _internal_ptr: *const c_void,
82
83    /// Number of `RefAny` instances sharing the same data.
84    /// When this reaches 0, the data is deallocated.
85    pub num_copies: AtomicUsize,
86
87    /// Number of active shared borrows (`Ref<T>`).
88    /// While > 0, mutable borrows are forbidden.
89    pub num_refs: AtomicUsize,
90
91    /// Number of active mutable borrows (`RefMut<T>`).
92    /// While > 0, all other borrows are forbidden.
93    pub num_mutable_refs: AtomicUsize,
94
95    /// Size of the stored type in bytes (from `size_of::<T>()`).
96    pub _internal_len: usize,
97
98    /// Layout size for deallocation (from `Layout::size()`).
99    pub _internal_layout_size: usize,
100
101    /// Required alignment for the stored type (from `align_of::<T>()`).
102    /// CRITICAL: Must match the alignment used during allocation to prevent UB.
103    pub _internal_layout_align: usize,
104
105    /// Runtime type identifier computed from `TypeId::of::<T>()`.
106    /// Used to prevent invalid downcasts.
107    pub type_id: u64,
108
109    /// Human-readable type name (e.g., "`MyStruct`") for debugging.
110    pub type_name: AzString,
111
112    /// Function pointer to correctly drop the type-erased data.
113    /// SAFETY: Must be called with a pointer to data of the correct type.
114    pub custom_destructor: extern "C" fn(*mut c_void),
115
116    /// Function pointer to serialize `RefAny` to JSON (0 = not set).
117    /// Cast to `RefAnySerializeFnType` (defined in `azul_layout::json`) when called.
118    /// Type: extern "C" fn(RefAny) -> Json
119    pub serialize_fn: usize,
120
121    /// Function pointer to deserialize JSON to new `RefAny` (0 = not set).
122    /// Cast to `RefAnyDeserializeFnType` (defined in `azul_layout::json`) when called.
123    /// Type: extern "C" fn(Json) -> `ResultRefAnyString`
124    pub deserialize_fn: usize,
125
126    /// Function pointer to an on-update observer (0 = not set).
127    /// Cast to `extern "C" fn(*const c_void, usize)` — the (data ptr, byte len)
128    /// of the *pre-mutation* data — and fired from `downcast_mut` BEFORE the
129    /// mutable borrow is handed out. This is the foundation for undo/redo
130    /// snapshots and client/server state sync. Set via `RefAny::set_update_fn`.
131    pub update_fn: usize,
132}
133
134/// Wrapper around a heap-allocated `RefCountInner`.
135///
136/// This is the shared metadata that all `RefAny` clones point to.
137/// The `RefCount` is responsible for all memory management:
138///
139/// - `RefCount::clone()` increments `num_copies` in `RefCountInner`
140/// - `RefCount::drop()` decrements `num_copies` and, if it reaches 0:
141///   1. Frees the `RefCountInner`
142///   2. Calls the custom destructor on the data
143///   3. Deallocates the data memory
144///
145/// # Why `run_destructor: bool`
146///
147/// This flag tracks whether this `RefCount` instance should decrement
148/// `num_copies` when dropped. Set to `true` for all clones (including
149/// those created by `RefAny::clone()` and `AZ_REFLECT` macros).
150/// Set to `false` after the decrement has been performed to prevent
151/// double-decrement.
152#[derive(Hash, PartialEq, PartialOrd, Ord, Eq)]
153#[repr(C)]
154pub struct RefCount {
155    pub ptr: *const RefCountInner,
156    pub run_destructor: bool,
157}
158
159impl fmt::Debug for RefCount {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        self.downcast().fmt(f)
162    }
163}
164
165impl Clone for RefCount {
166    /// Clones the `RefCount` and increments the reference count.
167    ///
168    /// # Safety
169    ///
170    /// This is safe because:
171    /// - The ptr is valid (created from `Box::into_raw`)
172    /// - `num_copies` is atomically incremented with `SeqCst` ordering
173    /// - This ensures the `RefCountInner` is not freed while clones exist
174    fn clone(&self) -> Self {
175        // CRITICAL: Must increment num_copies so the RefCountInner is not freed
176        // while this clone exists. The C macros (AZ_REFLECT) use AzRefCount_clone
177        // to create Ref/RefMut guards, and those guards must keep the data alive.
178        if !self.ptr.is_null() {
179            // SAFETY: `ptr` is non-null (checked) and came from `Box::into_raw`
180            // in `RefCount::new`; it stays alive as long as any clone exists
181            // because every clone increments `num_copies` here.
182            unsafe {
183                (*self.ptr).num_copies.fetch_add(1, AtomicOrdering::SeqCst);
184            }
185        }
186        Self {
187            ptr: self.ptr,
188            run_destructor: true,
189        }
190    }
191}
192
193impl Drop for RefCount {
194    /// Decrements the reference count when a `RefCount` clone is dropped.
195    ///
196    /// If this was the last reference (`num_copies` reaches 0), this will also
197    /// free the `RefCountInner` and call the custom destructor.
198    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
199    fn drop(&mut self) {
200        // Only decrement if run_destructor is true (meaning this is a clone)
201        // and the pointer is valid
202        if !self.run_destructor || self.ptr.is_null() {
203            return;
204        }
205        self.run_destructor = false;
206
207        // Take the inner pointer and NULL the field before doing anything
208        // else. The C ABI reaches this drop via `AzRefCount_delete` →
209        // `drop_in_place` on C-owned struct memory, and writes through
210        // `&mut self` persist in that memory. Nulling the pointer here
211        // (mirroring the `ptr = 0` convention the AZ_REFLECT C macros use
212        // for their downcast guards) makes a SECOND delete of the same
213        // struct — easy to hit in C example failure paths, and unguarded
214        // in pre-0.2.1 copies of azul.h — a safe no-op via the null check
215        // above, instead of a double-free of the RefCountInner allocation
216        // or a read through a dangling pointer.
217        let inner = self.ptr;
218        self.ptr = core::ptr::null();
219
220        // Atomically decrement and get the PREVIOUS value. `checked_sub`
221        // refuses to underflow: an unmatched decrement (e.g. a C caller
222        // deleting a byte-copied Ref struct twice) becomes a no-op instead
223        // of wrapping `num_copies` to `usize::MAX` and corrupting the
224        // reference count for the rest of the process.
225        // SAFETY: `inner` is non-null (guarded above) and points to the live
226        // `RefCountInner` from `Box::into_raw`; only the atomic field is touched.
227        let current_copies = unsafe {
228            match (*inner).num_copies.fetch_update(
229                AtomicOrdering::SeqCst,
230                AtomicOrdering::SeqCst,
231                |n| n.checked_sub(1),
232            ) {
233                Ok(prev) => prev,
234                Err(_zero) => return,
235            }
236        };
237
238        // If previous value wasn't 1, other references still exist
239        if current_copies != 1 {
240            return;
241        }
242
243        // We're the last reference! Clean up.
244        // SAFETY: ptr came from Box::into_raw, and we're the last reference
245        let sharing_info = unsafe { Box::from_raw(inner.cast_mut()) };
246        let sharing_info = *sharing_info; // Box deallocates RefCountInner here
247
248        // Get the data pointer
249        let data_ptr = sharing_info._internal_ptr;
250
251        // Handle zero-sized types specially
252        if sharing_info._internal_len == 0
253            || sharing_info._internal_layout_size == 0
254            || data_ptr.is_null()
255        {
256            let mut _dummy: [u8; 0] = [];
257            // Call destructor even for ZSTs (may have side effects)
258            (sharing_info.custom_destructor)(_dummy.as_mut_ptr().cast::<c_void>());
259        } else {
260            // Reconstruct the layout used during allocation. Removed the
261            // `unsafe { Layout::from_size_align_unchecked(..) }`: these size/align
262            // were produced by a valid `Layout` in `new_c` (`layout.size()` /
263            // `layout.align()`), so the safe checked constructor always succeeds
264            // and is behaviorally identical here — no unsafe needed.
265            let layout = Layout::from_size_align(
266                sharing_info._internal_layout_size,
267                sharing_info._internal_layout_align,
268            )
269            .expect("RefCount::drop: stored layout was invalid");
270
271            // Phase 1: Run the custom destructor
272            (sharing_info.custom_destructor)(data_ptr.cast_mut());
273
274            // Phase 2: Deallocate the memory
275            // SAFETY: `data_ptr` was allocated in `new_c` (or `replace_contents`)
276            // with exactly this `layout`, and we are the last reference, so no
277            // other clone can observe the freed block.
278            unsafe {
279                alloc::alloc::dealloc(data_ptr as *mut u8, layout);
280            }
281        }
282    }
283}
284
285/// Debug-friendly snapshot of `RefCountInner` with non-atomic values.
286#[derive(Debug, Clone)]
287pub(crate) struct RefCountInnerDebug {
288    pub(crate) num_copies: usize,
289    pub(crate) num_refs: usize,
290    pub(crate) num_mutable_refs: usize,
291    pub(crate) _internal_len: usize,
292    pub(crate) _internal_layout_size: usize,
293    pub(crate) _internal_layout_align: usize,
294    pub(crate) type_id: u64,
295    pub(crate) type_name: AzString,
296    pub(crate) custom_destructor: usize,
297    /// Serialization function pointer (0 = not set)
298    pub(crate) serialize_fn: usize,
299    /// Deserialization function pointer (0 = not set)
300    pub(crate) deserialize_fn: usize,
301}
302
303impl RefCount {
304    /// Creates a new `RefCount` by boxing the metadata on the heap.
305    ///
306    /// # Safety
307    ///
308    /// Safe because we're creating a new allocation with `Box::new`,
309    /// then immediately leaking it with `into_raw` to get a stable pointer.
310    fn new(ref_count: RefCountInner) -> Self {
311        Self {
312            ptr: Box::into_raw(Box::new(ref_count)),
313            run_destructor: true,
314        }
315    }
316
317    /// Dereferences the raw pointer to access the metadata.
318    ///
319    /// # Safety
320    ///
321    /// Safe because:
322    /// - The pointer is created from `Box::into_raw`, so it's valid and properly aligned
323    /// - The lifetime is tied to `&self`, ensuring the pointer is still alive
324    /// - Reference counting ensures the data isn't freed while references exist
325    fn downcast(&self) -> &RefCountInner {
326        assert!(!self.ptr.is_null(), "[RefCount::downcast] FATAL: self.ptr is null!");
327        // SAFETY: `ptr` is non-null (asserted) and came from `Box::into_raw`; the
328        // returned reference is bounded by `&self`, and refcounting keeps the
329        // `RefCountInner` alive for at least that long.
330        unsafe { &*self.ptr }
331    }
332
333    /// Creates a debug snapshot of the current reference counts.
334    ///
335    /// Loads all atomic values with `SeqCst` ordering to get a consistent view.
336    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
337    pub(crate) fn debug_get_refcount_copied(&self) -> RefCountInnerDebug {
338        let dc = self.downcast();
339        RefCountInnerDebug {
340            num_copies: dc.num_copies.load(AtomicOrdering::SeqCst),
341            num_refs: dc.num_refs.load(AtomicOrdering::SeqCst),
342            num_mutable_refs: dc.num_mutable_refs.load(AtomicOrdering::SeqCst),
343            _internal_len: dc._internal_len,
344            _internal_layout_size: dc._internal_layout_size,
345            _internal_layout_align: dc._internal_layout_align,
346            type_id: dc.type_id,
347            type_name: dc.type_name.clone(),
348            custom_destructor: dc.custom_destructor as usize,
349            serialize_fn: dc.serialize_fn,
350            deserialize_fn: dc.deserialize_fn,
351        }
352    }
353
354    /// Runtime check: can we create a shared borrow?
355    ///
356    /// Returns `true` if there are no active mutable borrows.
357    /// Multiple shared borrows can coexist (like `&T` in Rust).
358    ///
359    /// # Memory Ordering
360    ///
361    /// Uses `SeqCst` to ensure we see the most recent state from all threads.
362    /// If another thread just released a mutable borrow, we'll see it.
363    #[must_use] pub fn can_be_shared(&self) -> bool {
364        self.downcast()
365            .num_mutable_refs
366            .load(AtomicOrdering::SeqCst)
367            == 0
368    }
369
370    /// Runtime check: can we create a mutable borrow?
371    ///
372    /// Returns `true` only if there are ZERO active borrows of any kind.
373    /// This enforces Rust's exclusive mutability rule (like `&mut T`).
374    ///
375    /// # Memory Ordering
376    ///
377    /// Uses `SeqCst` to ensure we see all recent borrows from all threads.
378    /// Both counters must be checked atomically to prevent races.
379    #[must_use] pub fn can_be_shared_mut(&self) -> bool {
380        let info = self.downcast();
381        info.num_mutable_refs.load(AtomicOrdering::SeqCst) == 0
382            && info.num_refs.load(AtomicOrdering::SeqCst) == 0
383    }
384
385    /// Increments the shared borrow counter.
386    ///
387    /// Called when a `Ref<T>` is created. The `Ref::drop` will decrement it.
388    ///
389    /// # Memory Ordering
390    ///
391    /// `SeqCst` ensures this increment is visible to all threads before they
392    /// try to acquire a mutable borrow (which checks this counter).
393    pub fn increase_ref(&self) {
394        self.downcast()
395            .num_refs
396            .fetch_add(1, AtomicOrdering::SeqCst);
397    }
398
399    /// Decrements the shared borrow counter.
400    ///
401    /// Called when a `Ref<T>` is dropped, indicating the borrow is released.
402    ///
403    /// # Underflow guard
404    ///
405    /// Saturates at 0: an unmatched decrement — e.g. a C caller running
406    /// `FooRef_delete` after a FAILED downcast with a pre-0.2.1 copy of
407    /// `azul.h` (whose macro did not skip the decrease), or a plain
408    /// double-delete — must not wrap `num_refs` to `usize::MAX`, which
409    /// would make `can_be_shared_mut()` return `false` for the rest of
410    /// the process (callbacks silently stop mutating state).
411    ///
412    /// # Memory Ordering
413    ///
414    /// `SeqCst` ensures this decrement is immediately visible to other threads
415    /// waiting to acquire a mutable borrow.
416    pub fn decrease_ref(&self) {
417        let _ = self.downcast().num_refs.fetch_update(
418            AtomicOrdering::SeqCst,
419            AtomicOrdering::SeqCst,
420            |n| n.checked_sub(1),
421        );
422    }
423
424    /// Increments the mutable borrow counter.
425    ///
426    /// Called when a `RefMut<T>` is created. Should only succeed when this
427    /// counter and `num_refs` are both 0.
428    ///
429    /// # Memory Ordering
430    ///
431    /// `SeqCst` ensures this increment is visible to all other threads,
432    /// blocking them from acquiring any borrow (shared or mutable).
433    pub fn increase_refmut(&self) {
434        self.downcast()
435            .num_mutable_refs
436            .fetch_add(1, AtomicOrdering::SeqCst);
437    }
438
439    /// Decrements the mutable borrow counter.
440    ///
441    /// Called when a `RefMut<T>` is dropped, releasing exclusive access.
442    ///
443    /// # Underflow guard
444    ///
445    /// Saturates at 0 (see [`Self::decrease_ref`]): a double
446    /// `FooRefMut_delete` from C must not wrap `num_mutable_refs`, which
447    /// would corrupt the runtime borrow checker and let a second thread
448    /// or timer callback obtain an aliasing mutable borrow.
449    ///
450    /// # Memory Ordering
451    ///
452    /// `SeqCst` ensures this decrement is immediately visible, allowing
453    /// other threads to acquire borrows.
454    pub fn decrease_refmut(&self) {
455        let _ = self.downcast().num_mutable_refs.fetch_update(
456            AtomicOrdering::SeqCst,
457            AtomicOrdering::SeqCst,
458            |n| n.checked_sub(1),
459        );
460    }
461}
462
463/// RAII guard for a shared borrow of type `T` from a `RefAny`.
464///
465/// Similar to `std::cell::Ref`, this automatically decrements the borrow
466/// counter when dropped, ensuring borrows are properly released.
467///
468/// # Deref
469///
470/// Implements `Deref<Target = T>` so you can use it like `&T`.
471#[derive(Debug)]
472#[repr(C)]
473pub struct Ref<'a, T> {
474    ptr: &'a T,
475    sharing_info: RefCount,
476}
477
478impl<T> Drop for Ref<'_, T> {
479    /// Automatically releases the shared borrow when the guard goes out of scope.
480    ///
481    /// # Safety
482    ///
483    /// Safe because `decrease_ref` uses atomic operations and is designed to be
484    /// called exactly once per `Ref` instance.
485    fn drop(&mut self) {
486        self.sharing_info.decrease_ref();
487    }
488}
489
490impl<T> core::ops::Deref for Ref<'_, T> {
491    type Target = T;
492
493    fn deref(&self) -> &Self::Target {
494        self.ptr
495    }
496}
497
498/// RAII guard for a mutable borrow of type `T` from a `RefAny`.
499///
500/// Similar to `std::cell::RefMut`, this automatically decrements the mutable
501/// borrow counter when dropped, releasing exclusive access.
502///
503/// # Deref / `DerefMut`
504///
505/// Implements both `Deref` and `DerefMut` so you can use it like `&mut T`.
506#[derive(Debug)]
507#[repr(C)]
508pub struct RefMut<'a, T> {
509    ptr: &'a mut T,
510    sharing_info: RefCount,
511}
512
513impl<T> Drop for RefMut<'_, T> {
514    /// Automatically releases the mutable borrow when the guard goes out of scope.
515    ///
516    /// # Safety
517    ///
518    /// Safe because `decrease_refmut` uses atomic operations and is designed to be
519    /// called exactly once per `RefMut` instance.
520    fn drop(&mut self) {
521        self.sharing_info.decrease_refmut();
522    }
523}
524
525impl<T> core::ops::Deref for RefMut<'_, T> {
526    type Target = T;
527
528    fn deref(&self) -> &Self::Target {
529        &*self.ptr
530    }
531}
532
533impl<T> core::ops::DerefMut for RefMut<'_, T> {
534    fn deref_mut(&mut self) -> &mut Self::Target {
535        self.ptr
536    }
537}
538
539/// Type-erased, reference-counted smart pointer with runtime borrow checking.
540///
541/// `RefAny` is similar to `Arc<RefCell<dyn Any>>`, providing:
542/// - Type erasure (stores any `'static` type)
543/// - Reference counting (clones share the same data)
544/// - Runtime borrow checking (enforces Rust's borrowing rules at runtime)
545/// - FFI compatibility (`#[repr(C)]` and C-compatible API)
546///
547/// # Thread Safety
548///
549/// - `Send`: Can be moved between threads (heap-allocated data, atomic counters)
550/// - `Sync`: Can be shared between threads (`downcast_ref/mut` require `&mut self`)
551///
552/// # Memory Safety
553///
554/// Fixed critical UB bugs in alignment, copy count, and pointer provenance.
555/// All operations are verified with Miri to ensure absence of undefined behavior.
556///
557/// # Usage
558///
559/// ```rust
560/// # use azul_core::refany::RefAny;
561/// let data = RefAny::new(42i32);
562/// let mut data_clone = data.clone(); // shares the same heap allocation
563///
564/// // Runtime-checked downcasting with type safety
565/// if let Some(value_ref) = data_clone.downcast_ref::<i32>() {
566///     assert_eq!(*value_ref, 42);
567/// };
568///
569/// // Runtime-checked mutable borrowing
570/// if let Some(mut value_mut) = data_clone.downcast_mut::<i32>() {
571///     *value_mut = 100;
572/// };
573/// ```
574#[derive(Debug, Hash, PartialEq, PartialOrd, Ord, Eq)]
575#[repr(C)]
576pub struct RefAny {
577    /// Shared metadata: reference counts, type info, destructor, AND data pointer.
578    ///
579    /// All `RefAny` clones point to the same `RefCountInner` via this field.
580    /// The data pointer is stored in `RefCountInner` so all clones see the same
581    /// pointer, even after `replace_contents()` is called.
582    ///
583    /// The `run_destructor` flag on `RefCount` controls whether dropping this
584    /// `RefAny` should decrement the reference count and potentially free memory.
585    pub sharing_info: RefCount,
586
587    /// Unique ID for this specific clone (root = 0, subsequent clones increment).
588    ///
589    /// Used to distinguish between the original and clones for debugging.
590    pub instance_id: u64,
591}
592
593impl_option!(
594    RefAny,
595    OptionRefAny,
596    copy = false,
597    [Debug, Hash, Clone, PartialEq, PartialOrd, Ord, Eq]
598);
599
600// AUDIT: unsound-but-required. These `Send`/`Sync` impls are unconditional in
601// `T`: a `!Send`/`!Sync` payload moved or shared cross-thread races its own
602// internals. This is an INTENTIONAL FFI design constraint — `RefAny` is a
603// type-erased C-ABI handle with no way to carry `T: Send + Sync` bounds across
604// the boundary, and the framework's threading model keeps a given payload on
605// one thread in practice. Left as-is per the audit; do not "fix" by adding
606// bounds (it would break the erased FFI type).
607//
608// SAFETY: RefAny is Send because:
609// - The data pointer points to heap memory (can be sent between threads)
610// - All shared state (RefCountInner) uses atomic operations
611// - No thread-local storage is used
612#[allow(clippy::non_send_fields_in_send_ty)] // see SAFETY note above: atomic refcount, no TLS, no cross-thread deref
613unsafe impl Send for RefAny {}
614
615// SAFETY: RefAny is Sync because:
616// - Methods on `&RefAny` (like `clone`, `get_type_id`) only use atomic operations or
617//   read immutable data, which is inherently thread-safe
618// - The runtime borrow checker (via `can_be_shared/shared_mut`) uses SeqCst atomics
619//
620// AUDIT: unsound-but-required (same intentional FFI constraint as `Send` above).
621//
622// The check-then-increment race that this note described in `downcast_ref/mut`
623// is now FIXED (both use atomic `fetch_add`+validate / `compare_exchange`
624// acquisition — see those methods). The remaining unsoundness is only the
625// unconditional-in-`T` `Sync`, which is required by the erased C-ABI type.
626unsafe impl Sync for RefAny {}
627
628impl RefAny {
629    /// Creates a new type-erased `RefAny` containing the given value.
630    ///
631    /// This is the primary way to construct a `RefAny` from Rust code.
632    ///
633    /// # Type Safety
634    ///
635    /// Stores the `TypeId` of `T` for runtime type checking during downcasts.
636    ///
637    /// # Memory Layout
638    ///
639    /// - Allocates memory on the heap with correct size (`size_of::<T>()`) and alignment
640    ///   (`align_of::<T>()`)
641    /// - Copies the value into the heap allocation
642    /// - Forgets the original value to prevent double-drop
643    ///
644    /// # Custom Destructor
645    ///
646    /// Creates a type-specific destructor that:
647    /// 1. Copies the data from heap back to stack
648    /// 2. Calls `mem::drop` to run `T`'s destructor
649    /// 3. The heap memory is freed separately in `RefAny::drop`
650    ///
651    /// This two-phase destruction ensures proper cleanup even for complex types.
652    ///
653    /// # Safety
654    ///
655    /// Safe because:
656    /// - `mem::forget` prevents double-drop of the original value
657    /// - Type `T` and destructor `<U>` are matched at compile time
658    /// - `ptr::copy_nonoverlapping` with count=1 copies exactly one `T`
659    ///
660    /// # Example
661    ///
662    /// ```rust
663    /// # use azul_core::refany::RefAny;
664    /// let mut data = RefAny::new(42i32);
665    /// let value = data.downcast_ref::<i32>().unwrap();
666    /// assert_eq!(*value, 42);
667    /// ```
668    pub fn new<T: 'static>(value: T) -> Self {
669        /// Type-specific destructor that properly drops the inner value.
670        ///
671        /// # Safety
672        ///
673        /// Safe to call ONLY with a pointer that was created by `RefAny::new<U>`.
674        /// The type `U` must match the original type `T`.
675        ///
676        /// # Why Copy to Stack?
677        ///
678        /// Rust's drop glue expects a value, not a pointer. We copy the data
679        /// to the stack so `mem::drop` can run the destructor properly.
680        ///
681        /// # Critical Fix
682        ///
683        /// The third argument to `copy_nonoverlapping` is the COUNT (1 element),
684        /// not the SIZE in bytes. Using `size_of::<U>()` here would copy
685        /// `size_of::<U>()` elements, causing buffer overflow.
686        extern "C" fn default_custom_destructor<U: 'static>(ptr: *mut c_void) {
687            use core::{mem, ptr};
688
689            // The actual drop glue. `U::drop` is arbitrary user code and this
690            // function is `extern "C"` (called across the FFI boundary from the
691            // C ABI teardown), so a panic escaping here would unwind across that
692            // boundary = UB.
693            // SAFETY: this fn is only installed by `RefAny::new::<U>`, so `ptr`
694            // points to an initialized, properly aligned `U` that no other code
695            // still references (we are in the final drop). We move it out exactly
696            // once (`count = 1`) and run its drop glue.
697            let run = || unsafe {
698                // Allocate uninitialized stack space for one `U`
699                let mut stack_mem = mem::MaybeUninit::<U>::uninit();
700
701                // Copy 1 element of type U from heap to stack
702                ptr::copy_nonoverlapping(
703                    ptr as *const U,
704                    stack_mem.as_mut_ptr(),
705                    1, // CRITICAL: This is element count, not byte count!
706                );
707
708                // Take ownership and run the destructor
709                let stack_mem = stack_mem.assume_init();
710                drop(stack_mem); // Runs U's Drop implementation
711            };
712
713            // AUDIT: contain any panic from `U::drop` so it can't unwind across
714            // the `extern "C"` boundary. `catch_unwind` needs `std`; `no_std`
715            // builds use `panic = "abort"`, where unwinding cannot occur.
716            #[cfg(feature = "std")]
717            {
718                drop(std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)));
719            }
720            #[cfg(not(feature = "std"))]
721            {
722                run();
723            }
724        }
725
726        let type_name = ::core::any::type_name::<T>();
727        let type_id = Self::get_type_id_static::<T>();
728
729        let st = AzString::from_const_str(type_name);
730        let s = Self::new_c(
731            (&raw const value) as *const c_void,
732            ::core::mem::size_of::<T>(),
733            ::core::mem::align_of::<T>(), // CRITICAL: Pass alignment to prevent UB
734            type_id,
735            st,
736            default_custom_destructor::<T>,
737            0, // serialize_fn: not set for Rust types by default
738            0, // deserialize_fn: not set for Rust types by default
739        );
740        ::core::mem::forget(value); // Prevent double-drop
741        s
742    }
743
744    /// C-ABI compatible function to create a `RefAny` from raw components.
745    ///
746    /// This is the low-level constructor used by FFI bindings (C, Python, etc.).
747    ///
748    /// # Parameters
749    ///
750    /// - `ptr`: Pointer to the value to store (will be copied)
751    /// - `len`: Size of the value in bytes (`size_of::<T>()`)
752    /// - `align`: Required alignment in bytes (`align_of::<T>()`)
753    /// - `type_id`: Unique identifier for the type (for downcast safety)
754    /// - `type_name`: Human-readable type name (for debugging)
755    /// - `custom_destructor`: Function to call when the last reference is dropped
756    /// - `serialize_fn`: Function pointer for JSON serialization (0 = not set)
757    /// - `deserialize_fn`: Function pointer for JSON deserialization (0 = not set)
758    ///
759    /// # Safety
760    ///
761    /// Caller must ensure:
762    /// - `ptr` points to valid data of size `len` with alignment `align`
763    /// - `type_id` uniquely identifies the type
764    /// - `custom_destructor` correctly drops the type at `ptr`
765    /// - `len` and `align` match the actual type's layout
766    /// - If `serialize_fn != 0`, it must be a valid function pointer of type
767    ///   `extern "C" fn(RefAny) -> Json`
768    /// - If `deserialize_fn != 0`, it must be a valid function pointer of type
769    ///   `extern "C" fn(Json) -> ResultRefAnyString`
770    ///
771    /// # Zero-Sized Types
772    ///
773    /// Special case: ZSTs use a null pointer but still track the type info
774    /// and call the destructor (which may have side effects even for ZSTs).
775    ///
776    /// # Panics
777    ///
778    /// Panics if `ptr` is null while `len > 0` (a non-empty value must have a
779    /// valid backing pointer).
780    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
781    pub fn new_c(
782        // *const T
783        ptr: *const c_void,
784        // sizeof(T)
785        len: usize,
786        // alignof(T)
787        align: usize,
788        // unique ID of the type (used for type comparison when downcasting)
789        type_id: u64,
790        // name of the class such as "app::MyData", usually compiler- or macro-generated
791        type_name: AzString,
792        custom_destructor: extern "C" fn(*mut c_void),
793        // function pointer for JSON serialization (0 = not set)
794        serialize_fn: usize,
795        // function pointer for JSON deserialization (0 = not set)
796        deserialize_fn: usize,
797    ) -> Self {
798        use core::ptr;
799
800        // CRITICAL: Validate input pointer for non-ZST types
801        // A NULL pointer for a non-zero-sized type would cause UB when copying
802        assert!(!(len > 0 && ptr.is_null()), 
803                "RefAny::new_c: NULL pointer passed for non-ZST type (size={}). \
804                This would cause undefined behavior. Type: {:?}",
805                len,
806                type_name.as_str()
807            );
808
809        // Special case: Zero-sized types
810        //
811        // Calling `alloc(Layout { size: 0, .. })` is UB, so we use a null pointer.
812        // The destructor is still called (it may have side effects even for ZSTs).
813        let (_internal_ptr, layout) = if len == 0 {
814            let _dummy: [u8; 0] = [];
815            (ptr::null_mut(), Layout::for_value(&_dummy))
816        } else {
817            // CRITICAL FIX: Use the caller-provided alignment, not alignment of [u8]
818            //
819            // Previous bug: `Layout::for_value(&[u8])` created align=1
820            // This caused unaligned references when downcasting to types like i32 (align=4)
821            //
822            // Fixed: `Layout::from_size_align(len, align)` respects the type's alignment
823            let layout = Layout::from_size_align(len, align).expect("Failed to create layout");
824
825            // Allocate heap memory with correct alignment
826            // SAFETY: `layout` has non-zero size (this branch is `len != 0`), the
827            // required precondition for `alloc`; null return is handled below.
828            let heap_struct_as_bytes = unsafe { alloc::alloc::alloc(layout) };
829
830            // Handle allocation failure (aborts the program)
831            if heap_struct_as_bytes.is_null() {
832                alloc::alloc::handle_alloc_error(layout);
833            }
834
835            // Copy the data byte-by-byte to the heap
836            // SAFETY: Both pointers are valid, non-overlapping, and properly aligned
837            unsafe { ptr::copy_nonoverlapping(ptr as *const u8, heap_struct_as_bytes, len) };
838
839            (heap_struct_as_bytes, layout)
840        };
841
842        let ref_count_inner = RefCountInner {
843            _internal_ptr: _internal_ptr as *const c_void,
844            num_copies: AtomicUsize::new(1),       // This is the first instance
845            num_refs: AtomicUsize::new(0),         // No borrows yet
846            num_mutable_refs: AtomicUsize::new(0), // No mutable borrows yet
847            _internal_len: len,
848            _internal_layout_size: layout.size(),
849            _internal_layout_align: layout.align(),
850            type_id,
851            type_name,
852            custom_destructor,
853            serialize_fn,
854            deserialize_fn,
855            update_fn: 0, // on-update observer not set by default; see set_update_fn
856        };
857
858        let sharing_info = RefCount::new(ref_count_inner);
859
860        Self {
861            sharing_info,
862            instance_id: 0, // Root instance
863        }
864    }
865
866    /// Returns the raw data pointer for FFI downcasting.
867    ///
868    /// This is used by the `AZ_REFLECT` macros in C/C++ to access the
869    /// type-erased data pointer for downcasting operations.
870    ///
871    /// # Safety
872    ///
873    /// The returned pointer must only be dereferenced after verifying
874    /// the type ID matches the expected type. Callers are responsible
875    /// for proper type safety checks.
876    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
877    #[must_use] pub fn get_data_ptr(&self) -> *const c_void {
878        self.sharing_info.downcast()._internal_ptr
879    }
880
881    /// Returns the byte length of the type-erased payload behind
882    /// [`Self::get_data_ptr`] (`size_of::<T>()` of the stored type;
883    /// `0` for ZSTs).
884    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
885    #[must_use] pub fn get_data_len(&self) -> usize {
886        self.sharing_info.downcast()._internal_len
887    }
888
889    /// Checks if this is the only `RefAny` instance with no active borrows.
890    ///
891    /// Returns `true` only if:
892    /// - `num_copies == 1` (no clones exist)
893    /// - `num_refs == 0` (no shared borrows active)
894    /// - `num_mutable_refs == 0` (no mutable borrows active)
895    ///
896    /// Useful for checking if you have exclusive ownership.
897    ///
898    /// # Memory Ordering
899    ///
900    /// Uses `SeqCst` to ensure a consistent view across all three counters.
901    pub(crate) fn has_no_copies(&self) -> bool {
902        self.sharing_info
903            .downcast()
904            .num_copies
905            .load(AtomicOrdering::SeqCst)
906            == 1
907            && self
908                .sharing_info
909                .downcast()
910                .num_refs
911                .load(AtomicOrdering::SeqCst)
912                == 0
913            && self
914                .sharing_info
915                .downcast()
916                .num_mutable_refs
917                .load(AtomicOrdering::SeqCst)
918                == 0
919    }
920
921    /// Attempts to downcast to a shared reference of type `U`.
922    ///
923    /// Returns `None` if:
924    /// - The stored type doesn't match `U` (type safety)
925    /// - A mutable borrow is already active (borrow checking)
926    /// - The pointer is null (ZST or uninitialized)
927    ///
928    /// # Type Safety
929    ///
930    /// Compares `type_id` at runtime before casting. This prevents casting
931    /// `*const c_void` to the wrong type, which would be immediate UB.
932    ///
933    /// # Borrow Checking
934    ///
935    /// Checks `can_be_shared()` to enforce Rust's borrowing rules:
936    /// - Multiple shared borrows are allowed
937    /// - Shared and mutable borrows cannot coexist
938    ///
939    /// # Safety
940    ///
941    /// The `unsafe` cast is safe because:
942    /// - Type ID check ensures `U` matches the stored type
943    /// - Memory was allocated with correct alignment for `U`
944    /// - Lifetime `'a` is tied to `&'a mut self`, preventing use-after-free
945    /// - Reference count is incremented atomically before returning
946    ///
947    /// # Why `&mut self`?
948    ///
949    /// Requires `&mut self` to prevent multiple threads from calling this
950    /// simultaneously on the same `RefAny`. The borrow checker enforces this.
951    /// Clones of the `RefAny` can call this independently (they share data
952    /// but have separate runtime borrow tracking).
953    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
954    #[inline]
955    pub fn downcast_ref<U: 'static>(&mut self) -> Option<Ref<'_, U>> {
956        // Runtime type check: prevent downcasting to wrong type
957        let stored_type_id = self.get_type_id();
958        let target_type_id = Self::get_type_id_static::<U>();
959        let is_same_type = stored_type_id == target_type_id;
960
961        if !is_same_type {
962            return None;
963        }
964
965        // AUDIT: ATOMIC shared-borrow acquisition.
966        //
967        // `RefAny` is `Sync` and clones share one `RefCountInner`, so the old
968        // check-then-increment (`can_be_shared()` then `increase_ref()`) raced a
969        // concurrent `downcast_mut` on another clone: both could pass their
970        // pre-checks and hand out aliasing `&`/`&mut` to the same memory (UB).
971        //
972        // Fix (mirrors the `compare_exchange` discipline in `replace_contents`):
973        // increment `num_refs` FIRST, then validate that no mutable borrow is
974        // live. `SeqCst` imposes a single total order, so a writer (which CASes
975        // `num_mutable_refs` 0->1 then reads `num_refs`) and this reader (which
976        // adds to `num_refs` then reads `num_mutable_refs`) can never both
977        // succeed — at least one observes the other's write. Back the increment
978        // out on any failure path.
979        self.sharing_info.increase_ref();
980
981        if !self.sharing_info.can_be_shared() {
982            // A mutable borrow is (being) acquired — release and fail.
983            self.sharing_info.decrease_ref();
984            return None;
985        }
986
987        // Get data pointer from shared RefCountInner (stable while we hold the
988        // shared borrow: `replace_contents` needs `num_refs == 0` to proceed).
989        let data_ptr = self.sharing_info.downcast()._internal_ptr;
990
991        // Null check: ZSTs or uninitialized
992        if data_ptr.is_null() {
993            self.sharing_info.decrease_ref();
994            return None;
995        }
996
997        Some(Ref {
998            // SAFETY: Type check passed, pointer is non-null and properly aligned
999            ptr: unsafe { &*(data_ptr as *const U) },
1000            sharing_info: self.sharing_info.clone(),
1001        })
1002    }
1003
1004    /// Attempts to downcast to a mutable reference of type `U`.
1005    ///
1006    /// Returns `None` if:
1007    /// - The stored type doesn't match `U` (type safety)
1008    /// - Any borrow is already active (borrow checking)
1009    /// - The pointer is null (ZST or uninitialized)
1010    ///
1011    /// # Type Safety
1012    ///
1013    /// Compares `type_id` at runtime before casting, preventing UB.
1014    ///
1015    /// # Borrow Checking
1016    ///
1017    /// Checks `can_be_shared_mut()` to enforce exclusive mutability:
1018    /// - No other borrows (shared or mutable) can be active
1019    /// - This is Rust's `&mut T` rule, enforced at runtime
1020    ///
1021    /// # Safety
1022    ///
1023    /// The `unsafe` cast is safe because:
1024    ///
1025    /// - Type ID check ensures `U` matches the stored type
1026    /// - Memory was allocated with correct alignment for `U`
1027    /// - Borrow check ensures no other references exist
1028    /// - Lifetime `'a` is tied to `&'a mut self`, preventing aliasing
1029    /// - Mutable reference count is incremented atomically
1030    ///
1031    /// # Memory Ordering
1032    ///
1033    /// The `increase_refmut()` uses `SeqCst`, ensuring other threads see
1034    /// this mutable borrow before they try to acquire any borrow.
1035    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
1036    #[inline]
1037    pub fn downcast_mut<U: 'static>(&mut self) -> Option<RefMut<'_, U>> {
1038        // Runtime type check
1039        let is_same_type = self.get_type_id() == Self::get_type_id_static::<U>();
1040        if !is_same_type {
1041            return None;
1042        }
1043
1044        // AUDIT: ATOMIC exclusive-borrow acquisition (mirror `replace_contents`).
1045        //
1046        // The old check-then-increment (`can_be_shared_mut()` then
1047        // `increase_refmut()`) raced concurrent borrows on sibling clones and
1048        // could hand out an aliasing `&mut` (UB). Instead, `compare_exchange`
1049        // `num_mutable_refs` 0->1 to atomically take the exclusive slot, THEN
1050        // verify no shared borrow is live; release + fail otherwise. The CAS
1051        // both acquires and rejects a second mutable borrow in one step.
1052        let inner = self.sharing_info.downcast();
1053        if inner
1054            .num_mutable_refs
1055            .compare_exchange(0, 1, AtomicOrdering::SeqCst, AtomicOrdering::SeqCst)
1056            .is_err()
1057        {
1058            return None;
1059        }
1060        if inner.num_refs.load(AtomicOrdering::SeqCst) != 0 {
1061            // A shared borrow is live — release the exclusive slot and fail.
1062            inner.num_mutable_refs.store(0, AtomicOrdering::SeqCst);
1063            return None;
1064        }
1065
1066        // Get data pointer from shared RefCountInner
1067        let data_ptr = inner._internal_ptr;
1068
1069        // Null check
1070        if data_ptr.is_null() {
1071            inner.num_mutable_refs.store(0, AtomicOrdering::SeqCst);
1072            return None;
1073        }
1074
1075        // Fire the on-update observer (if registered) BEFORE handing out the
1076        // mutable borrow: the callback sees the pre-mutation data + its byte
1077        // length, enabling undo/redo snapshots and client/server state sync.
1078        let update_fn = inner.update_fn;
1079        if update_fn != 0 {
1080            // SAFETY: `update_fn` is non-zero (checked) and, per `set_update_fn`'s
1081            // contract, is a valid `extern "C" fn(*const c_void, usize)`.
1082            let cb: extern "C" fn(*const c_void, usize) =
1083                unsafe { core::mem::transmute(update_fn) };
1084            let len = inner._internal_len;
1085            // AUDIT: the observer is a host-provided `extern "C"` fn. A Rust
1086            // panic escaping it would unwind across the FFI boundary (UB), so
1087            // contain it. `catch_unwind` needs `std`; `no_std` builds use
1088            // `panic = "abort"` where no unwinding can occur.
1089            #[cfg(feature = "std")]
1090            {
1091                drop(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1092                    cb(data_ptr, len);
1093                })));
1094            }
1095            #[cfg(not(feature = "std"))]
1096            {
1097                cb(data_ptr, len);
1098            }
1099        }
1100
1101        Some(RefMut {
1102            // SAFETY: Type and borrow checks passed, exclusive access guaranteed
1103            ptr: unsafe { &mut *(data_ptr as *mut U) },
1104            sharing_info: self.sharing_info.clone(),
1105        })
1106    }
1107
1108    /// Computes a runtime type ID from Rust's `TypeId`.
1109    ///
1110    /// Rust's `TypeId` is not `#[repr(C)]` and can't cross FFI boundaries.
1111    /// This function converts it to a `u64` by treating it as a byte array.
1112    ///
1113    /// # Safety
1114    ///
1115    /// Safe because:
1116    /// - `TypeId` is a valid type with a stable layout
1117    /// - We only read from it, never write
1118    /// - The slice lifetime is bounded by the function scope
1119    ///
1120    /// # Implementation
1121    ///
1122    /// Treats the `TypeId` as bytes and sums them with bit shifts to create
1123    /// a unique (but not cryptographically secure) hash.
1124    #[inline]
1125    fn get_type_id_static<T: 'static>() -> u64 {
1126        use core::{any::TypeId, mem};
1127
1128        let t_id = TypeId::of::<T>();
1129
1130        // SAFETY: TypeId is a valid type, we're only reading it
1131        let struct_as_bytes = unsafe {
1132            core::slice::from_raw_parts(
1133                (&raw const t_id) as *const u8,
1134                size_of::<TypeId>(),
1135            )
1136        };
1137
1138        // AUDIT: fold ALL bytes of the `TypeId` (16 on current toolchains),
1139        // not just the first 8. This u64 is the ONLY runtime type guard used by
1140        // `downcast_*`; dropping the high 8 bytes let two distinct types whose
1141        // `TypeId`s differ only in their upper half collide, permitting a
1142        // wrong-type downcast (UB). An FxHash-style rotate+multiply mixes every
1143        // byte into the result and is deterministic within a process run (which
1144        // is all `TypeId` itself guarantees).
1145        struct_as_bytes.iter().fold(0u64, |hash, &b| {
1146            (hash.rotate_left(5) ^ u64::from(b)).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95)
1147        })
1148    }
1149
1150    /// Checks if the stored type matches the given type ID.
1151    #[must_use] pub fn is_type(&self, type_id: u64) -> bool {
1152        self.sharing_info.downcast().type_id == type_id
1153    }
1154
1155    /// Returns the stored type ID.
1156    #[must_use] pub fn get_type_id(&self) -> u64 {
1157        self.sharing_info.downcast().type_id
1158    }
1159
1160    /// Returns the human-readable type name for debugging.
1161    #[must_use] pub fn get_type_name(&self) -> AzString {
1162        self.sharing_info.downcast().type_name.clone()
1163    }
1164
1165    /// Returns the current reference count (number of `RefAny` clones sharing this data).
1166    ///
1167    /// This is useful for debugging and metadata purposes.
1168    #[must_use] pub fn get_ref_count(&self) -> usize {
1169        self.sharing_info
1170            .downcast()
1171            .num_copies
1172            .load(AtomicOrdering::SeqCst)
1173    }
1174
1175    /// Returns the serialize function pointer (0 = not set).
1176    /// 
1177    /// This is used for JSON serialization of `RefAny` contents.
1178    #[must_use] pub fn get_serialize_fn(&self) -> usize {
1179        self.sharing_info.downcast().serialize_fn
1180    }
1181
1182    /// Returns the deserialize function pointer (0 = not set).
1183    /// 
1184    /// This is used for JSON deserialization to create a new `RefAny`.
1185    #[must_use] pub fn get_deserialize_fn(&self) -> usize {
1186        self.sharing_info.downcast().deserialize_fn
1187    }
1188
1189    /// Sets the serialize function pointer.
1190    ///
1191    /// # Safety
1192    ///
1193    /// The caller must ensure the function pointer is valid and has the correct
1194    /// signature: `extern "C" fn(RefAny) -> Json`
1195    ///
1196    /// **Known issue:** `&mut self` is exclusive to this clone, not to the shared
1197    /// `RefCountInner`. Concurrent calls via different clones are a data race
1198    /// because `serialize_fn` is a plain `usize`, not atomic.
1199    pub fn set_serialize_fn(&mut self, serialize_fn: usize) {
1200        // FIXME: &mut self is exclusive to this clone only, not to the shared
1201        // RefCountInner — concurrent calls via different clones are a data race.
1202        let inner = self.sharing_info.ptr.cast_mut();
1203        // SAFETY: `inner` came from `Box::into_raw` and is live (we hold `self`).
1204        unsafe {
1205            (*inner).serialize_fn = serialize_fn;
1206        }
1207    }
1208
1209    /// Sets the deserialize function pointer.
1210    ///
1211    /// # Safety
1212    ///
1213    /// The caller must ensure the function pointer is valid and has the correct
1214    /// signature: `extern "C" fn(Json) -> ResultRefAnyString`
1215    ///
1216    /// **Known issue:** `&mut self` is exclusive to this clone, not to the shared
1217    /// `RefCountInner`. Concurrent calls via different clones are a data race
1218    /// because `deserialize_fn` is a plain `usize`, not atomic.
1219    pub fn set_deserialize_fn(&mut self, deserialize_fn: usize) {
1220        // FIXME: &mut self is exclusive to this clone only, not to the shared
1221        // RefCountInner — concurrent calls via different clones are a data race.
1222        let inner = self.sharing_info.ptr.cast_mut();
1223        // SAFETY: `inner` came from `Box::into_raw` and is live (we hold `self`).
1224        unsafe {
1225            (*inner).deserialize_fn = deserialize_fn;
1226        }
1227    }
1228
1229    /// Registers an on-update observer (`0` = unset). It is fired from
1230    /// [`Self::downcast_mut`] with the (data ptr, byte len) of the *pre-mutation*
1231    /// data, just before the mutable borrow is handed out — the foundation for
1232    /// undo/redo snapshots and client/server state sync.
1233    ///
1234    /// # Safety
1235    ///
1236    /// If `update_fn != 0` it must be a valid `extern "C" fn(*const c_void, usize)`.
1237    /// Same shared-`RefCountInner` caveat as [`Self::set_serialize_fn`]: `&mut self`
1238    /// is exclusive to this clone, not to the shared inner.
1239    pub fn set_update_fn(&mut self, update_fn: usize) {
1240        let inner = self.sharing_info.ptr.cast_mut();
1241        // SAFETY: `inner` came from `Box::into_raw` and is live (we hold `self`).
1242        unsafe {
1243            (*inner).update_fn = update_fn;
1244        }
1245    }
1246
1247    /// Returns the registered on-update observer fn pointer (`0` = unset).
1248    #[must_use] pub fn get_update_fn(&self) -> usize {
1249        self.sharing_info.downcast().update_fn
1250    }
1251
1252    /// Returns true if this `RefAny` supports JSON serialization.
1253    #[must_use] pub fn can_serialize(&self) -> bool {
1254        self.get_serialize_fn() != 0
1255    }
1256
1257    /// Returns true if this `RefAny` type supports JSON deserialization.
1258    #[must_use] pub fn can_deserialize(&self) -> bool {
1259        self.get_deserialize_fn() != 0
1260    }
1261
1262    /// Replaces the contents of this `RefAny` with a new value from another `RefAny`.
1263    ///
1264    /// This method:
1265    /// 1. Atomically acquires a mutable "lock" via `compare_exchange`
1266    /// 2. Calls the destructor on the old value
1267    /// 3. Deallocates the old memory
1268    /// 4. Copies the new value's memory
1269    /// 5. Updates metadata (`type_id`, `type_name`, destructor, serialize/deserialize fns)
1270    /// 6. Updates the shared _`internal_ptr` so ALL clones see the new data
1271    /// 7. Releases the lock
1272    ///
1273    /// Since all clones of a `RefAny` share the same `RefCountInner`, this change
1274    /// will be visible to ALL clones of this `RefAny`.
1275    ///
1276    /// # Returns
1277    ///
1278    /// - `true` if the replacement was successful
1279    /// - `false` if there are active borrows (would cause UB)
1280    ///
1281    /// # Thread Safety
1282    ///
1283    /// Uses `compare_exchange` to atomically acquire exclusive access, preventing
1284    /// any race condition between checking for borrows and modifying the data.
1285    ///
1286    /// # Safety
1287    ///
1288    /// Safe because:
1289    /// - We atomically acquire exclusive access before modifying
1290    /// - The old destructor is called before deallocation
1291    /// - Memory is properly allocated with correct alignment
1292    /// - All metadata is updated while holding the lock
1293    ///
1294    /// # Panics
1295    ///
1296    /// Panics if a memory `Layout` for the replacement value cannot be
1297    /// constructed (its size overflows `isize::MAX`).
1298    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is required
1299    pub fn replace_contents(&mut self, new_value: Self) -> bool {
1300        use core::ptr;
1301
1302        let inner = self.sharing_info.ptr.cast_mut();
1303        
1304        // Atomically acquire exclusive access by setting num_mutable_refs to 1.
1305        // This uses compare_exchange to ensure no race condition:
1306        // - If num_mutable_refs is 0, set it to 1 (success)
1307        // - If num_mutable_refs is not 0, someone else has it (fail)
1308        // We also need to check num_refs == 0 atomically.
1309        let inner_ref = self.sharing_info.downcast();
1310        
1311        // First, try to acquire the mutable lock
1312        let mutable_lock_result = inner_ref.num_mutable_refs.compare_exchange(
1313            0,  // expected: no mutable refs
1314            1,  // desired: we take the mutable ref
1315            AtomicOrdering::SeqCst,
1316            AtomicOrdering::SeqCst,
1317        );
1318        
1319        if mutable_lock_result.is_err() {
1320            // Someone else has a mutable reference
1321            return false;
1322        }
1323        
1324        // Now check that there are no shared references
1325        // Note: We hold the mutable lock, so no new shared refs can be acquired
1326        if inner_ref.num_refs.load(AtomicOrdering::SeqCst) != 0 {
1327            // Release the lock and fail
1328            inner_ref.num_mutable_refs.store(0, AtomicOrdering::SeqCst);
1329            return false;
1330        }
1331        
1332        // We now have exclusive access - perform the replacement
1333        // SAFETY: we hold the exclusive lock (num_mutable_refs==1, num_refs==0),
1334        // so no live `Ref`/`RefMut` aliases the data; `inner` is the live
1335        // `RefCountInner` from `Box::into_raw`. Old data is destructed+freed with
1336        // its own stored layout before the pointer is overwritten, and the new
1337        // data is freshly allocated and byte-copied.
1338        unsafe {
1339            // Get old layout info before we overwrite it
1340            let old_ptr = (*inner)._internal_ptr;
1341            let old_len = (*inner)._internal_len;
1342            let old_layout_size = (*inner)._internal_layout_size;
1343            let old_layout_align = (*inner)._internal_layout_align;
1344            let old_destructor = (*inner).custom_destructor;
1345
1346            // Step 1: Call destructor on old value (if non-ZST)
1347            if old_len > 0 && !old_ptr.is_null() {
1348                old_destructor(old_ptr.cast_mut());
1349            }
1350
1351            // Step 2: Deallocate old memory (if non-ZST). Use the *checked*
1352            // `Layout::from_size_align` (not `_unchecked`): the stored
1353            // size/align came from a valid `Layout`, so it always succeeds, and
1354            // this shrinks the unchecked surface inside this unsafe block.
1355            if old_layout_size > 0 && !old_ptr.is_null() {
1356                let old_layout = Layout::from_size_align(old_layout_size, old_layout_align)
1357                    .expect("replace_contents: stored old layout was invalid");
1358                alloc::alloc::dealloc(old_ptr as *mut u8, old_layout);
1359            }
1360
1361            // Get new value's metadata
1362            let new_inner = new_value.sharing_info.downcast();
1363            let new_ptr = new_inner._internal_ptr;
1364            let new_len = new_inner._internal_len;
1365            let new_layout_size = new_inner._internal_layout_size;
1366            let new_layout_align = new_inner._internal_layout_align;
1367
1368            // Step 3: Allocate new memory and copy data
1369            let allocated_ptr = if new_len == 0 {
1370                ptr::null_mut()
1371            } else {
1372                let new_layout = Layout::from_size_align(new_len, new_layout_align)
1373                    .expect("Failed to create layout");
1374                let heap_ptr = alloc::alloc::alloc(new_layout);
1375                if heap_ptr.is_null() {
1376                    alloc::alloc::handle_alloc_error(new_layout);
1377                }
1378                // Copy data from new_value
1379                ptr::copy_nonoverlapping(
1380                    new_ptr as *const u8,
1381                    heap_ptr,
1382                    new_len,
1383                );
1384                heap_ptr
1385            };
1386
1387            // Step 4: Update the shared internal pointer in RefCountInner
1388            // All clones will see this new pointer!
1389            (*inner)._internal_ptr = allocated_ptr as *const c_void;
1390
1391            // Step 5: Update metadata in RefCountInner
1392            (*inner)._internal_len = new_len;
1393            (*inner)._internal_layout_size = new_layout_size;
1394            (*inner)._internal_layout_align = new_layout_align;
1395            (*inner).type_id = new_inner.type_id;
1396            (*inner).type_name = new_inner.type_name.clone();
1397            (*inner).custom_destructor = new_inner.custom_destructor;
1398            (*inner).serialize_fn = new_inner.serialize_fn;
1399            (*inner).deserialize_fn = new_inner.deserialize_fn;
1400            (*inner).update_fn = new_inner.update_fn;
1401        }
1402
1403        // Release the mutable lock
1404        self.sharing_info.downcast().num_mutable_refs.store(0, AtomicOrdering::SeqCst);
1405
1406        // AUDIT: reclaim `new_value` instead of leaking it.
1407        //
1408        // The old code `mem::forget(new_value)` to stop `RefAny::drop` from
1409        // running the T-destructor a SECOND time on the bytes we just copied
1410        // into our own allocation — but that leaked `new_value`'s entire
1411        // `RefCountInner` box AND its heap data block on every single call.
1412        //
1413        // Instead, neutralize `new_value`'s destructor to a no-op and let the
1414        // normal refcount teardown run: it frees BOTH allocations (data block +
1415        // inner box) when this was the last reference, without re-running the
1416        // real T-destructor (which now lives on OUR inner, to run exactly once
1417        // when `self` is finally dropped). If `new_value` still had clones, the
1418        // no-op keeps them from double-dropping the shared T while their own
1419        // last drop still reclaims the shared block — no double free, no leak.
1420        #[allow(clippy::items_after_statements)]
1421        const extern "C" fn noop_destructor(_: *mut c_void) {}
1422        let new_inner = new_value.sharing_info.ptr.cast_mut();
1423        if !new_inner.is_null() {
1424            // SAFETY: `new_inner` came from `Box::into_raw` in `RefCount::new`
1425            // and is still alive (we hold `new_value`).
1426            unsafe {
1427                (*new_inner).custom_destructor = noop_destructor;
1428            }
1429        }
1430        drop(new_value);
1431
1432        true
1433    }
1434}
1435
1436impl Clone for RefAny {
1437    /// Creates a new `RefAny` sharing the same heap-allocated data.
1438    ///
1439    /// This is cheap (just increments a counter) and is how multiple parts
1440    /// of the code can hold references to the same data.
1441    ///
1442    /// # Reference Counting
1443    ///
1444    /// Atomically increments `num_copies` with `SeqCst` ordering before
1445    /// creating the clone. This ensures all threads see the updated count
1446    /// before the clone can be used.
1447    ///
1448    /// # Instance ID
1449    ///
1450    /// Each clone gets a unique `instance_id` based on the current copy count.
1451    /// The original has `instance_id=0`, the first clone gets `1`, etc.
1452    ///
1453    /// # Memory Ordering
1454    ///
1455    /// The `fetch_add` followed by `load` both use `SeqCst`:
1456    /// - `fetch_add`: Ensures the increment is visible to all threads
1457    /// - `load`: Gets the updated value for the `instance_id`
1458    ///
1459    /// This prevents race conditions where two threads clone simultaneously
1460    /// and both see the same `instance_id`.
1461    ///
1462    /// # Safety
1463    ///
1464    /// Safe because:
1465    ///
1466    /// - Atomic operations prevent data races
1467    /// - The heap allocation remains valid (only freed when count reaches 0)
1468    /// - `run_destructor` is set to `true` for all clones
1469    fn clone(&self) -> Self {
1470        // Atomically increment the reference count
1471        let inner = self.sharing_info.downcast();
1472        let prev = inner.num_copies.fetch_add(1, AtomicOrdering::SeqCst);
1473
1474        let new_instance_id = (prev + 1) as u64;
1475
1476        Self {
1477            // Data pointer is now in RefCountInner, shared automatically
1478            sharing_info: RefCount {
1479                ptr: self.sharing_info.ptr, // Share the same metadata (and data pointer)
1480                run_destructor: true,       // This clone should decrement num_copies on drop
1481            },
1482            // Give this clone a unique ID based on the updated count
1483            instance_id: new_instance_id,
1484        }
1485    }
1486}
1487
1488impl Drop for RefAny {
1489    /// Empty drop implementation - all cleanup is handled by `RefCount::drop`.
1490    ///
1491    /// When a `RefAny` is dropped, its `sharing_info: RefCount` field is automatically
1492    /// dropped by Rust. The `RefCount::drop` implementation handles all cleanup:
1493    ///
1494    /// 1. Atomically decrements `num_copies` with `fetch_sub`
1495    /// 2. If the previous value was 1 (we're the last reference):
1496    ///    - Reclaims the `RefCountInner` via `Box::from_raw`
1497    ///    - Calls the custom destructor to run `T::drop()`
1498    ///    - Deallocates the heap memory with the stored layout
1499    ///
1500    /// # Why No Code Here?
1501    ///
1502    /// Previously, `RefAny::drop` handled cleanup, but this caused issues with the
1503    /// C API where `Ref<T>` and `RefMut<T>` guards (which clone the `RefCount`) need
1504    /// to keep the data alive even after the original `RefAny` is dropped.
1505    ///
1506    /// By moving all cleanup to `RefCount::drop`, we ensure that:
1507    /// - `RefAny::clone()` creates a `RefCount` with `run_destructor = true`
1508    /// - `AZ_REFLECT` macros create `Ref`/`RefMut` guards that clone `RefCount`
1509    /// - Each `RefCount` drop decrements the counter
1510    /// - Only the LAST drop (when `num_copies` was 1) cleans up memory
1511    ///
1512    /// See `RefCount::drop` for the full algorithm and safety documentation.
1513    fn drop(&mut self) {
1514        // RefCount::drop handles everything automatically.
1515        // The sharing_info field is dropped by Rust, triggering RefCount::drop.
1516    }
1517}
1518
1519#[cfg(test)]
1520#[allow(clippy::items_after_statements, clippy::redundant_clone, clippy::cast_possible_truncation, clippy::cast_sign_loss, trivial_casts, clippy::borrow_as_ptr, clippy::cast_ptr_alignment, clippy::unused_self, unused_qualifications, unreachable_pub, private_interfaces)] // pedantic lints are noise in unsafe-exercising test code
1521mod audit_tests {
1522    use super::*;
1523    use core::sync::atomic::{AtomicUsize, Ordering};
1524
1525    static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
1526
1527    struct DropCounter(#[allow(dead_code)] u32);
1528    impl Drop for DropCounter {
1529        fn drop(&mut self) {
1530            DROP_COUNT.fetch_add(1, Ordering::SeqCst);
1531        }
1532    }
1533
1534    // AUDIT: exclusive borrow must be denied while a shared borrow is live and
1535    // vice-versa (runtime borrow checker), and must be recoverable after the
1536    // guard drops. Exercises the atomic acquire/release added to downcast_*.
1537    #[test]
1538    fn borrow_exclusion_and_recovery() {
1539        // The runtime borrow guard lives in the *shared* refcount inner, so it
1540        // is only observable across two clones (a single `RefAny` can't hold two
1541        // guards at once — the methods take `&mut self`). `b` shares `a`'s inner.
1542        let mut a = RefAny::new(7i32);
1543        let mut b = a.clone();
1544
1545        {
1546            let r = a.downcast_ref::<i32>().unwrap();
1547            assert_eq!(*r, 7);
1548            // shared borrow live -> no mutable borrow via the shared inner
1549            assert!(b.downcast_mut::<i32>().is_none());
1550            // another shared borrow is fine
1551            assert!(b.downcast_ref::<i32>().is_some());
1552        }
1553
1554        {
1555            let mut m = a.downcast_mut::<i32>().unwrap();
1556            *m = 42;
1557            // mutable borrow live -> no shared borrow via the shared inner
1558            assert!(b.downcast_ref::<i32>().is_none());
1559        }
1560
1561        assert_eq!(*a.downcast_ref::<i32>().unwrap(), 42);
1562    }
1563
1564    // AUDIT: wrong-type downcast must be rejected. Same type -> same id.
1565    #[test]
1566    fn type_id_guard() {
1567        let mut a = RefAny::new(1u64);
1568        assert!(a.downcast_ref::<i32>().is_none());
1569        assert!(a.downcast_ref::<u64>().is_some());
1570
1571        assert_eq!(
1572            RefAny::get_type_id_static::<u64>(),
1573            RefAny::get_type_id_static::<u64>()
1574        );
1575        assert_ne!(
1576            RefAny::get_type_id_static::<u64>(),
1577            RefAny::get_type_id_static::<i64>()
1578        );
1579    }
1580
1581    // AUDIT: replace_contents must run each stored value's destructor exactly
1582    // once (old value on replace, new value on final drop) and must not leak.
1583    #[test]
1584    fn replace_contents_drops_exactly_once() {
1585        DROP_COUNT.store(0, Ordering::SeqCst);
1586        {
1587            let mut a = RefAny::new(DropCounter(1));
1588            let b = RefAny::new(DropCounter(2));
1589            assert!(a.replace_contents(b));
1590            // The original `a` value was dropped during replacement.
1591            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
1592            // `a` now holds the (copied) `b` value; dropped at end of scope.
1593        }
1594        // Two DropCounter values were constructed; both must be dropped once.
1595        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 2);
1596    }
1597
1598    // AUDIT: replace_contents must fail (return false) while a borrow is live.
1599    #[test]
1600    fn replace_contents_denied_while_borrowed() {
1601        let mut a = RefAny::new(1i32);
1602        // Clone first: `r` will exclusively borrow `a`, so the sibling clone
1603        // must exist beforehand. Both share the same inner RefCountInner.
1604        let mut a2 = a.clone();
1605        let r = a.downcast_ref::<i32>().unwrap();
1606        // A live shared borrow (num_refs != 0) on the shared inner must block
1607        // replace_contents via the sibling clone.
1608        assert!(!a2.replace_contents(RefAny::new(2i32)));
1609        drop(r);
1610        assert!(a2.replace_contents(RefAny::new(2i32)));
1611    }
1612
1613    // ---- Miri-focused unit tests -------------------------------------------
1614    // These exercise the pure-Rust memory behavior of each unsafe path so Miri
1615    // can detect UB (bad provenance, misalignment, use-after-free, leaks,
1616    // refcount corruption). No FFI, no threads, no OS calls; tiny allocations.
1617
1618    // MIRI: covers RefAny::new + new_c alloc/copy_nonoverlapping + downcast_ref
1619    // (&*(ptr as *const U)) + the final Drop path (Box::from_raw + dealloc +
1620    // custom destructor). A non-Copy heap type checks the destructor runs.
1621    #[test]
1622    fn miri_new_downcast_drop_roundtrip() {
1623        DROP_COUNT.store(0, Ordering::SeqCst);
1624        {
1625            let mut a = RefAny::new(DropCounter(9));
1626            // downcast_ref exercises the type-id guard + aligned pointer cast.
1627            assert!(a.downcast_ref::<DropCounter>().is_some());
1628            assert!(a.downcast_ref::<u8>().is_none());
1629        }
1630        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
1631    }
1632
1633    // MIRI: alignment correctness of new_c's Layout::from_size_align path. An
1634    // over-aligned payload downcast to a misaligned pointer would be UB.
1635    #[test]
1636    fn miri_alignment_preserved() {
1637        #[repr(align(16))]
1638        #[derive(Debug)]
1639        struct Over(u64);
1640        let mut a = RefAny::new(Over(0xABCD));
1641        let r = a.downcast_ref::<Over>().unwrap();
1642        assert_eq!(r.0, 0xABCD);
1643        assert_eq!((&raw const *r) as usize % 16, 0);
1644    }
1645
1646    // MIRI: clone shares one RefCountInner; num_copies increments on clone and
1647    // decrements on drop (RefCount::clone / RefCount::drop fetch paths). Data
1648    // must survive while any clone lives and be freed exactly once at the end.
1649    #[test]
1650    fn miri_clone_refcount_increment_decrement() {
1651        DROP_COUNT.store(0, Ordering::SeqCst);
1652        {
1653            let a = RefAny::new(DropCounter(1));
1654            assert_eq!(a.get_ref_count(), 1);
1655            let b = a.clone();
1656            assert_eq!(a.get_ref_count(), 2);
1657            assert_eq!(b.get_ref_count(), 2);
1658            {
1659                let c = b.clone();
1660                assert_eq!(c.get_ref_count(), 3);
1661            }
1662            // c dropped -> back to 2, nothing freed yet.
1663            assert_eq!(a.get_ref_count(), 2);
1664            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0);
1665        }
1666        // all clones dropped -> data destructed exactly once.
1667        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
1668    }
1669
1670    // MIRI: downcast_mut hands out &mut *(ptr as *mut U); mutation must be
1671    // visible through a shared clone (shared RefCountInner data pointer).
1672    #[test]
1673    fn miri_downcast_mut_mutation_visible_across_clones() {
1674        let mut a = RefAny::new(10u32);
1675        let mut b = a.clone();
1676        {
1677            let mut m = a.downcast_mut::<u32>().unwrap();
1678            *m += 5;
1679        }
1680        assert_eq!(*b.downcast_ref::<u32>().unwrap(), 15);
1681    }
1682
1683    // MIRI: the runtime borrow refcount on the shared inner. Exercises
1684    // increase_ref/decrease_ref/increase_refmut/decrease_refmut and the
1685    // can_be_shared / can_be_shared_mut predicates directly, plus the
1686    // checked_sub underflow guard (decrement at zero must saturate, not wrap).
1687    #[test]
1688    fn miri_borrow_counter_transitions_and_underflow_guard() {
1689        let a = RefAny::new(0i32);
1690        let rc = &a.sharing_info;
1691
1692        assert!(rc.can_be_shared());
1693        assert!(rc.can_be_shared_mut());
1694
1695        rc.increase_ref();
1696        assert!(rc.can_be_shared()); // shared borrows coexist
1697        assert!(!rc.can_be_shared_mut()); // but block a mutable borrow
1698        rc.decrease_ref();
1699        assert!(rc.can_be_shared_mut());
1700
1701        rc.increase_refmut();
1702        assert!(!rc.can_be_shared()); // mutable borrow blocks shared
1703        assert!(!rc.can_be_shared_mut());
1704        rc.decrease_refmut();
1705        assert!(rc.can_be_shared_mut());
1706
1707        // Underflow guard: extra decrements must saturate at 0, never wrap to
1708        // usize::MAX (which would permanently break the borrow checker).
1709        rc.decrease_ref();
1710        rc.decrease_refmut();
1711        assert!(rc.can_be_shared());
1712        assert!(rc.can_be_shared_mut());
1713    }
1714
1715    // MIRI: get_type_id_static reads TypeId via from_raw_parts and folds ALL
1716    // bytes. Same type -> same id (stable within a run); distinct types differ.
1717    #[test]
1718    fn miri_type_id_static_stable_and_distinct() {
1719        assert_eq!(
1720            RefAny::get_type_id_static::<(u8, u64)>(),
1721            RefAny::get_type_id_static::<(u8, u64)>()
1722        );
1723        assert_ne!(
1724            RefAny::get_type_id_static::<u32>(),
1725            RefAny::get_type_id_static::<[u32; 2]>()
1726        );
1727    }
1728
1729    // MIRI: ZST payload uses a null data pointer but must still construct,
1730    // clone, run its destructor once, and reject downcasts (null ptr path).
1731    #[test]
1732    fn miri_zst_roundtrip_and_destructor() {
1733        DROP_COUNT.store(0, Ordering::SeqCst);
1734        struct ZstDrop;
1735        impl Drop for ZstDrop {
1736            fn drop(&mut self) {
1737                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
1738            }
1739        }
1740        {
1741            let mut a = RefAny::new(ZstDrop);
1742            assert_eq!(a.get_data_len(), 0);
1743            // downcast_ref bails on the null data pointer for a ZST.
1744            assert!(a.downcast_ref::<ZstDrop>().is_none());
1745            let _b = a.clone();
1746        }
1747        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
1748    }
1749
1750    // MIRI: replace_contents alloc/dealloc/copy path plus the neutralized
1751    // new_value destructor. Old value destructed once, new value destructed
1752    // once at final drop, with no leak/double-free of either heap block.
1753    #[test]
1754    fn miri_replace_contents_alloc_paths() {
1755        DROP_COUNT.store(0, Ordering::SeqCst);
1756        {
1757            let mut a = RefAny::new(DropCounter(1));
1758            assert!(a.replace_contents(RefAny::new(DropCounter(2))));
1759            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1); // old value gone
1760            assert_eq!(a.downcast_ref::<DropCounter>().unwrap().0, 2u32);
1761        }
1762        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 2);
1763    }
1764
1765    // MIRI: replacing across differing sizes/alignments (u8 -> u64) reallocates
1766    // correctly and keeps the shared pointer aligned for the new type.
1767    #[test]
1768    fn miri_replace_contents_changes_layout() {
1769        let mut a = RefAny::new(7u8);
1770        assert!(a.replace_contents(RefAny::new(0x1122_3344_5566_7788u64)));
1771        {
1772            // downcast_ref takes &mut self, so scope the guard before the next call.
1773            let r = a.downcast_ref::<u64>().unwrap();
1774            assert_eq!(*r, 0x1122_3344_5566_7788u64);
1775            assert_eq!((&raw const *r) as usize % core::mem::align_of::<u64>(), 0);
1776        }
1777        // old u8 type must no longer downcast.
1778        assert!(a.downcast_ref::<u8>().is_none());
1779    }
1780
1781    // MIRI: RefCount clone/drop in isolation keeps the inner alive until the
1782    // last handle drops (Box::into_raw / Box::from_raw balance).
1783    #[test]
1784    fn miri_refcount_clone_keeps_inner_alive() {
1785        let a = RefAny::new(5usize);
1786        let rc0 = a.sharing_info.clone(); // +1 copy
1787        let rc1 = rc0.clone(); // +1 copy
1788        assert_eq!(a.get_ref_count(), 3);
1789        drop(rc1);
1790        drop(rc0);
1791        assert_eq!(a.get_ref_count(), 1);
1792        // `a` still usable -> inner not freed.
1793        assert_eq!(*a.clone().downcast_ref::<usize>().unwrap(), 5);
1794    }
1795}
1796
1797#[cfg(test)]
1798#[allow(
1799    clippy::items_after_statements,
1800    clippy::redundant_clone,
1801    clippy::needless_pass_by_value,
1802    clippy::needless_range_loop,
1803    clippy::cast_possible_truncation,
1804    clippy::cast_sign_loss,
1805    clippy::cast_lossless,
1806    clippy::float_cmp,
1807    clippy::unreadable_literal,
1808    clippy::unusual_byte_groupings,
1809    clippy::many_single_char_names,
1810    clippy::used_underscore_binding,
1811    clippy::borrow_as_ptr,
1812    clippy::cast_ptr_alignment,
1813    clippy::fn_to_numeric_cast_any,
1814    trivial_casts,
1815    unused_qualifications,
1816    unreachable_pub,
1817    private_interfaces,
1818    missing_debug_implementations,
1819    missing_copy_implementations
1820)] // pedantic lints are noise in unsafe-exercising test code
1821mod autotest_generated {
1822    use alloc::{string::String, vec::Vec};
1823    use core::{
1824        ffi::c_void,
1825        sync::atomic::{AtomicUsize, Ordering},
1826    };
1827
1828    use super::*;
1829
1830    /// Destructor for payloads that need no drop glue (`Copy` types built via
1831    /// the raw C-ABI `new_c` path).
1832    extern "C" fn noop_destructor(_: *mut c_void) {}
1833
1834    /// Store `value` in a `RefAny` and read it back out: the byte-copy into the
1835    /// heap allocation and the type-checked pointer cast must be lossless.
1836    fn round_trip<T: 'static + Clone + PartialEq + core::fmt::Debug>(value: T) {
1837        let mut a = RefAny::new(value.clone());
1838        let r = a
1839            .downcast_ref::<T>()
1840            .expect("downcast to the stored type must succeed");
1841        assert_eq!(*r, value);
1842    }
1843
1844    // ---- RefAny::new_c — raw C-ABI constructor, malformed/boundary inputs ----
1845
1846    // A NULL pointer with a non-zero length is the classic FFI mistake: copying
1847    // from it would be UB, so `new_c` must panic instead of reading it.
1848    #[test]
1849    #[should_panic(expected = "NULL pointer passed for non-ZST type")]
1850    fn new_c_null_ptr_with_nonzero_len_panics() {
1851        drop(RefAny::new_c(
1852            core::ptr::null(),
1853            4,
1854            4,
1855            RefAny::get_type_id_static::<u32>(),
1856            AzString::from_const_str("autotest::NullPtr"),
1857            noop_destructor,
1858            0,
1859            0,
1860        ));
1861    }
1862
1863    // A non-power-of-two alignment cannot form a valid `Layout`; it must panic
1864    // before allocating rather than allocate with a bogus layout (which would
1865    // make the matching `dealloc` in `drop` UB).
1866    #[test]
1867    #[should_panic(expected = "Failed to create layout")]
1868    fn new_c_non_power_of_two_align_panics() {
1869        let value: u32 = 7;
1870        drop(RefAny::new_c(
1871            (&raw const value).cast::<c_void>(),
1872            4,
1873            3, // not a power of two
1874            RefAny::get_type_id_static::<u32>(),
1875            AzString::from_const_str("autotest::BadAlign"),
1876            noop_destructor,
1877            0,
1878            0,
1879        ));
1880    }
1881
1882    // `usize::MAX` bytes overflows `isize::MAX` and cannot be a `Layout`: the
1883    // checked constructor must reject it (no silent overflow into a tiny alloc).
1884    #[test]
1885    #[should_panic(expected = "Failed to create layout")]
1886    fn new_c_huge_len_panics_instead_of_overflowing() {
1887        let value: u8 = 1;
1888        drop(RefAny::new_c(
1889            (&raw const value).cast::<c_void>(),
1890            usize::MAX,
1891            1,
1892            RefAny::get_type_id_static::<u8>(),
1893            AzString::from_const_str("autotest::HugeLen"),
1894            noop_destructor,
1895            0,
1896            0,
1897        ));
1898    }
1899
1900    // len == 0 is the ZST path: NULL data pointer is legal, `align` is ignored
1901    // (even a nonsensical 0), nothing is allocated, and downcasts fail cleanly.
1902    #[test]
1903    fn new_c_zero_len_null_ptr_is_a_clean_zst() {
1904        let mut a = RefAny::new_c(
1905            core::ptr::null(),
1906            0,
1907            0, // invalid alignment, but unused on the ZST path
1908            RefAny::get_type_id_static::<()>(),
1909            AzString::from_const_str("autotest::Zst"),
1910            noop_destructor,
1911            0,
1912            0,
1913        );
1914        assert_eq!(a.get_data_len(), 0);
1915        assert!(a.get_data_ptr().is_null());
1916        assert!(a.is_type(RefAny::get_type_id_static::<()>()));
1917        // Type matches, but there is no data behind the pointer -> None, and the
1918        // borrow counters must be released again on that bail-out path.
1919        assert!(a.downcast_ref::<()>().is_none());
1920        assert!(a.downcast_mut::<()>().is_none());
1921        assert!(a.sharing_info.can_be_shared_mut());
1922    }
1923
1924    // Round-trip through the raw C-ABI constructor: what `new_c` encodes,
1925    // `downcast_ref` must decode bit-for-bit.
1926    #[test]
1927    fn new_c_round_trip_matches_rust_constructor() {
1928        let value: u64 = 0xDEAD_BEEF_CAFE_BABE;
1929        let mut a = RefAny::new_c(
1930            (&raw const value).cast::<c_void>(),
1931            core::mem::size_of::<u64>(),
1932            core::mem::align_of::<u64>(),
1933            RefAny::get_type_id_static::<u64>(),
1934            AzString::from_const_str("u64"),
1935            noop_destructor,
1936            7,
1937            9,
1938        );
1939        assert_eq!(a.get_data_len(), core::mem::size_of::<u64>());
1940        assert_eq!(a.get_ref_count(), 1);
1941        assert_eq!(a.get_serialize_fn(), 7);
1942        assert_eq!(a.get_deserialize_fn(), 9);
1943        assert!(a.can_serialize());
1944        assert!(a.can_deserialize());
1945        assert_eq!(*a.downcast_ref::<u64>().unwrap(), value);
1946    }
1947
1948    // The runtime guard is the type ID, nothing else: a matching size, name and
1949    // destructor must NOT be enough to downcast if the ID differs by one bit.
1950    #[test]
1951    fn new_c_wrong_type_id_rejects_downcast() {
1952        let value: u64 = 0x0102_0304_0506_0708;
1953        let real_id = RefAny::get_type_id_static::<u64>();
1954        let mut a = RefAny::new_c(
1955            (&raw const value).cast::<c_void>(),
1956            core::mem::size_of::<u64>(),
1957            core::mem::align_of::<u64>(),
1958            real_id ^ 1, // one bit off
1959            AzString::from_const_str("u64"),
1960            noop_destructor,
1961            0,
1962            0,
1963        );
1964        assert!(!a.is_type(real_id));
1965        assert!(a.downcast_ref::<u64>().is_none());
1966        assert!(a.downcast_mut::<u64>().is_none());
1967        // The rejected downcasts must not have left a borrow behind.
1968        assert!(a.sharing_info.can_be_shared_mut());
1969    }
1970
1971    // Over-alignment (align > len) is a valid `Layout`; the payload must land on
1972    // an address that satisfies the requested alignment.
1973    #[test]
1974    fn new_c_over_aligned_small_payload() {
1975        let value: u8 = 0x5A;
1976        let mut a = RefAny::new_c(
1977            (&raw const value).cast::<c_void>(),
1978            1,
1979            16,
1980            RefAny::get_type_id_static::<u8>(),
1981            AzString::from_const_str("u8"),
1982            noop_destructor,
1983            0,
1984            0,
1985        );
1986        assert_eq!(a.get_data_ptr() as usize % 16, 0);
1987        assert_eq!(*a.downcast_ref::<u8>().unwrap(), 0x5A);
1988    }
1989
1990    // The type name is arbitrary caller-supplied UTF-8 (generated by foreign
1991    // codegen): empty, unicode, RTL overrides and embedded NULs must survive.
1992    #[test]
1993    fn new_c_preserves_unicode_and_empty_type_names() {
1994        let value: u32 = 0;
1995        let weird = "app::💥Ünïcødé<T>\u{202E}rtl\u{0}nul";
1996        let a = RefAny::new_c(
1997            (&raw const value).cast::<c_void>(),
1998            4,
1999            4,
2000            1,
2001            AzString::from(String::from(weird)),
2002            noop_destructor,
2003            0,
2004            0,
2005        );
2006        assert_eq!(a.get_type_name().as_str(), weird);
2007
2008        let b = RefAny::new_c(
2009            (&raw const value).cast::<c_void>(),
2010            4,
2011            4,
2012            2,
2013            AzString::from_const_str(""),
2014            noop_destructor,
2015            0,
2016            0,
2017        );
2018        assert_eq!(b.get_type_name().as_str(), "");
2019    }
2020
2021    // ---- RefAny::new — post-construction invariants ----
2022
2023    #[test]
2024    fn new_invariants_hold() {
2025        let mut a = RefAny::new(0x1122_3344u32);
2026        assert_eq!(a.get_data_len(), core::mem::size_of::<u32>());
2027        assert!(!a.get_data_ptr().is_null());
2028        assert_eq!(a.get_data_ptr() as usize % core::mem::align_of::<u32>(), 0);
2029        assert_eq!(a.get_type_id(), RefAny::get_type_id_static::<u32>());
2030        assert!(a.is_type(RefAny::get_type_id_static::<u32>()));
2031        assert_eq!(a.get_type_name().as_str(), "u32");
2032        assert_eq!(a.get_ref_count(), 1);
2033        assert!(a.has_no_copies());
2034        assert_eq!(a.get_serialize_fn(), 0);
2035        assert_eq!(a.get_deserialize_fn(), 0);
2036        assert_eq!(a.get_update_fn(), 0);
2037        assert!(!a.can_serialize());
2038        assert!(!a.can_deserialize());
2039        assert!(a.sharing_info.can_be_shared());
2040        assert!(a.sharing_info.can_be_shared_mut());
2041        assert_eq!(a.instance_id, 0);
2042        assert_eq!(*a.downcast_ref::<u32>().unwrap(), 0x1122_3344);
2043    }
2044
2045    // A zero-length array of an 8-aligned element is still a ZST: `new` must take
2046    // the null-pointer path (no zero-size allocation, which would be UB).
2047    #[test]
2048    fn new_zero_sized_array_of_aligned_type_is_a_zst() {
2049        let mut a = RefAny::new([0u64; 0]);
2050        assert_eq!(a.get_data_len(), 0);
2051        assert!(a.get_data_ptr().is_null());
2052        assert_eq!(
2053            a.sharing_info.debug_get_refcount_copied()._internal_layout_size,
2054            0
2055        );
2056        assert!(a.downcast_ref::<[u64; 0]>().is_none());
2057        assert_eq!(a.get_ref_count(), 1);
2058    }
2059
2060    // Large + heavily over-aligned payload: the alignment recorded at
2061    // construction must be honoured by the allocation, or every downcast would
2062    // hand out a misaligned reference.
2063    #[test]
2064    fn new_large_over_aligned_payload_round_trips() {
2065        #[repr(align(64))]
2066        #[derive(Clone)]
2067        struct Big([u8; 4096]);
2068
2069        let mut a = RefAny::new(Big([0xAB; 4096]));
2070        assert_eq!(a.get_data_len(), 4096);
2071        assert_eq!(a.get_data_ptr() as usize % 64, 0);
2072        let r = a.downcast_ref::<Big>().unwrap();
2073        assert_eq!((&raw const *r) as usize % 64, 0);
2074        assert!(r.0.iter().all(|&b| b == 0xAB));
2075    }
2076
2077    // ---- numeric limits / round-trip ----
2078
2079    #[test]
2080    fn integer_limits_round_trip() {
2081        round_trip(u8::MIN);
2082        round_trip(u8::MAX);
2083        round_trip(i8::MIN);
2084        round_trip(i8::MAX);
2085        round_trip(u16::MAX);
2086        round_trip(i16::MIN);
2087        round_trip(u32::MAX);
2088        round_trip(i32::MIN);
2089        round_trip(u64::MAX);
2090        round_trip(i64::MIN);
2091        // u128/i128 are 16-aligned on most targets -> exercises the align path
2092        round_trip(u128::MAX);
2093        round_trip(i128::MIN);
2094        round_trip(i128::MAX);
2095        round_trip(usize::MAX);
2096        round_trip(isize::MIN);
2097        round_trip(0usize);
2098    }
2099
2100    // Floats are copied as raw bytes, so every bit pattern (NaN payloads, signed
2101    // zero, infinities) must survive unchanged — no normalization, no rounding.
2102    #[test]
2103    fn float_extremes_round_trip_bit_exact() {
2104        let mut nan = RefAny::new(f64::NAN);
2105        assert!(nan.downcast_ref::<f64>().unwrap().is_nan());
2106
2107        // A NaN with a non-canonical payload must come back bit-identical.
2108        let bits = 0x7FF0_0000_0000_0001u64;
2109        let mut payload_nan = RefAny::new(f64::from_bits(bits));
2110        assert_eq!(payload_nan.downcast_ref::<f64>().unwrap().to_bits(), bits);
2111
2112        let mut neg_zero = RefAny::new(-0.0f64);
2113        let nz = neg_zero.downcast_ref::<f64>().unwrap();
2114        assert!(*nz == 0.0 && nz.is_sign_negative());
2115        drop(nz);
2116
2117        let mut inf = RefAny::new(f32::NEG_INFINITY);
2118        assert_eq!(*inf.downcast_ref::<f32>().unwrap(), f32::NEG_INFINITY);
2119        // f32 and f64 are distinct types even though both are "floats".
2120        assert!(inf.downcast_ref::<f64>().is_none());
2121
2122        round_trip(f64::MIN);
2123        round_trip(f64::MAX);
2124        round_trip(f64::MIN_POSITIVE);
2125        round_trip(f32::EPSILON);
2126        round_trip(f32::MAX);
2127    }
2128
2129    // Owned heap payloads: the value is moved in (`mem::forget` on the original)
2130    // and dropped exactly once at the end — a double-drop here would be a
2131    // double-free of the String/Vec buffers.
2132    #[test]
2133    fn owned_unicode_payloads_round_trip() {
2134        round_trip(String::new());
2135        round_trip(String::from("héllo 🌍 \u{202E}rtl\u{0}nul"));
2136        round_trip('🌍');
2137
2138        let mut v: Vec<String> = Vec::new();
2139        v.push(String::from("a"));
2140        v.push(String::from("🎉"));
2141        v.push(String::new());
2142        round_trip(v);
2143    }
2144
2145    // A struct with interior padding is byte-copied, padding included: the copy
2146    // must not disturb the initialized fields.
2147    #[test]
2148    fn padded_struct_round_trips() {
2149        #[derive(Clone, PartialEq, Debug)]
2150        #[repr(C)]
2151        struct Padded {
2152            a: u8,
2153            b: u64,
2154            c: u8,
2155        }
2156        round_trip(Padded {
2157            a: 0xFF,
2158            b: u64::MAX,
2159            c: 0x01,
2160        });
2161    }
2162
2163    // ---- setters: 0 / 1 / usize::MAX (never dereferenced by azul-core) ----
2164
2165    #[test]
2166    fn set_serialize_fn_zero_and_extremes() {
2167        let mut a = RefAny::new(1u32);
2168        assert_eq!(a.get_serialize_fn(), 0);
2169        assert!(!a.can_serialize());
2170
2171        a.set_serialize_fn(usize::MAX);
2172        assert_eq!(a.get_serialize_fn(), usize::MAX);
2173        assert!(a.can_serialize());
2174
2175        a.set_serialize_fn(1);
2176        assert_eq!(a.get_serialize_fn(), 1);
2177        assert!(a.can_serialize());
2178
2179        a.set_serialize_fn(0);
2180        assert_eq!(a.get_serialize_fn(), 0);
2181        assert!(!a.can_serialize());
2182
2183        // The fn pointer lives in the SHARED inner, so a clone's setter is
2184        // visible through the original.
2185        let mut b = a.clone();
2186        b.set_serialize_fn(42);
2187        assert_eq!(a.get_serialize_fn(), 42);
2188        assert!(a.can_serialize());
2189        b.set_serialize_fn(0);
2190        assert!(!a.can_serialize());
2191    }
2192
2193    #[test]
2194    fn set_deserialize_fn_zero_and_extremes() {
2195        let mut a = RefAny::new(1u32);
2196        assert_eq!(a.get_deserialize_fn(), 0);
2197        assert!(!a.can_deserialize());
2198
2199        a.set_deserialize_fn(usize::MAX);
2200        assert_eq!(a.get_deserialize_fn(), usize::MAX);
2201        assert!(a.can_deserialize());
2202
2203        a.set_deserialize_fn(1);
2204        assert_eq!(a.get_deserialize_fn(), 1);
2205
2206        a.set_deserialize_fn(0);
2207        assert_eq!(a.get_deserialize_fn(), 0);
2208        assert!(!a.can_deserialize());
2209
2210        let mut b = a.clone();
2211        b.set_deserialize_fn(42);
2212        assert_eq!(a.get_deserialize_fn(), 42);
2213        b.set_deserialize_fn(0);
2214        assert!(!a.can_deserialize());
2215    }
2216
2217    // `set_update_fn` only *stores* the address; a bogus value must round-trip
2218    // and must be resettable to 0. (Deliberately no `downcast_mut` while the
2219    // observer is bogus — `downcast_mut` transmutes and CALLS it.)
2220    #[test]
2221    fn set_update_fn_zero_and_extremes() {
2222        let mut a = RefAny::new(1u32);
2223        assert_eq!(a.get_update_fn(), 0);
2224
2225        a.set_update_fn(usize::MAX);
2226        assert_eq!(a.get_update_fn(), usize::MAX);
2227
2228        a.set_update_fn(0);
2229        assert_eq!(a.get_update_fn(), 0);
2230        // With the observer unset again, mutable borrows work as normal.
2231        assert!(a.downcast_mut::<u32>().is_some());
2232    }
2233
2234    // The registered observer must fire exactly once per *successful*
2235    // `downcast_mut`, and must see the PRE-mutation bytes + the payload length.
2236    static UPDATE_CALLS: AtomicUsize = AtomicUsize::new(0);
2237    static UPDATE_LEN: AtomicUsize = AtomicUsize::new(0);
2238    static UPDATE_PRE_VALUE: AtomicUsize = AtomicUsize::new(0);
2239
2240    extern "C" fn record_update(ptr: *const c_void, len: usize) {
2241        UPDATE_CALLS.fetch_add(1, Ordering::SeqCst);
2242        UPDATE_LEN.store(len, Ordering::SeqCst);
2243        if !ptr.is_null() && len == core::mem::size_of::<u32>() {
2244            // SAFETY: only installed on a `RefAny` holding a `u32`, and
2245            // `downcast_mut` fires it with that live payload pointer.
2246            let pre = unsafe { core::ptr::read_unaligned(ptr.cast::<u32>()) };
2247            UPDATE_PRE_VALUE.store(pre as usize, Ordering::SeqCst);
2248        }
2249    }
2250
2251    #[test]
2252    fn update_fn_fires_once_with_pre_mutation_data() {
2253        UPDATE_CALLS.store(0, Ordering::SeqCst);
2254
2255        let mut a = RefAny::new(7u32);
2256        let cb: extern "C" fn(*const c_void, usize) = record_update;
2257        a.set_update_fn(cb as usize);
2258        assert_eq!(a.get_update_fn(), cb as usize);
2259
2260        {
2261            let mut m = a.downcast_mut::<u32>().unwrap();
2262            *m = 9;
2263        }
2264        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
2265        assert_eq!(UPDATE_LEN.load(Ordering::SeqCst), 4);
2266        // The observer saw 7, not 9: it runs BEFORE the borrow is handed out.
2267        assert_eq!(UPDATE_PRE_VALUE.load(Ordering::SeqCst), 7);
2268
2269        // A wrong-type downcast must not fire it.
2270        assert!(a.downcast_mut::<u64>().is_none());
2271        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
2272
2273        // A shared borrow is not a mutation -> must not fire it.
2274        assert_eq!(*a.downcast_ref::<u32>().unwrap(), 9);
2275        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
2276
2277        // A *denied* mutable borrow (shared borrow live on a sibling clone)
2278        // must not fire it either.
2279        let mut b = a.clone();
2280        let r = a.downcast_ref::<u32>().unwrap();
2281        assert!(b.downcast_mut::<u32>().is_none());
2282        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
2283        drop(r);
2284
2285        // Unregistering stops the observer.
2286        b.set_update_fn(0);
2287        assert!(b.downcast_mut::<u32>().is_some());
2288        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
2289    }
2290
2291    // ---- predicates ----
2292
2293    #[test]
2294    fn is_type_true_false_and_extremes() {
2295        let a = RefAny::new(0u32);
2296        let id = a.get_type_id();
2297
2298        assert!(a.is_type(id));
2299        assert!(!a.is_type(!id)); // every bit flipped -> always a different id
2300        assert!(!a.is_type(id.wrapping_add(1)));
2301        assert!(!a.is_type(RefAny::get_type_id_static::<i32>()));
2302        if id != 0 {
2303            assert!(!a.is_type(0));
2304        }
2305        if id != u64::MAX {
2306            assert!(!a.is_type(u64::MAX));
2307        }
2308    }
2309
2310    #[test]
2311    fn has_no_copies_transitions() {
2312        let mut a = RefAny::new(1u32);
2313        assert!(a.has_no_copies());
2314
2315        {
2316            let b = a.clone();
2317            assert!(!a.has_no_copies()); // num_copies == 2
2318            assert!(!b.has_no_copies());
2319        }
2320        assert!(a.has_no_copies()); // clone dropped -> exclusive again
2321
2322        {
2323            // A live shared borrow (taken via a sibling clone) also disqualifies.
2324            let mut c = a.clone();
2325            let r = c.downcast_ref::<u32>().unwrap();
2326            assert_eq!(*r, 1);
2327            assert!(!a.has_no_copies());
2328        }
2329        assert!(a.has_no_copies());
2330
2331        {
2332            let mut c = a.clone();
2333            let m = c.downcast_mut::<u32>().unwrap();
2334            assert_eq!(*m, 1);
2335            assert!(!a.has_no_copies());
2336        }
2337        assert!(a.has_no_copies());
2338    }
2339
2340    #[test]
2341    fn can_serialize_and_can_deserialize_track_the_fn_pointers() {
2342        let mut a = RefAny::new(1u32);
2343        assert!(!a.can_serialize());
2344        assert!(!a.can_deserialize());
2345
2346        a.set_serialize_fn(1);
2347        assert!(a.can_serialize());
2348        assert!(!a.can_deserialize());
2349
2350        a.set_deserialize_fn(usize::MAX);
2351        assert!(a.can_serialize());
2352        assert!(a.can_deserialize());
2353
2354        a.set_serialize_fn(0);
2355        a.set_deserialize_fn(0);
2356        assert!(!a.can_serialize());
2357        assert!(!a.can_deserialize());
2358    }
2359
2360    // ---- getters ----
2361
2362    #[test]
2363    fn get_ref_count_tracks_clones_and_borrow_guards() {
2364        let mut a = RefAny::new(5u8);
2365        assert_eq!(a.get_ref_count(), 1);
2366
2367        let mut b = a.clone();
2368        assert_eq!(a.get_ref_count(), 2);
2369        assert_eq!(b.get_ref_count(), 2);
2370
2371        {
2372            // The guard clones the RefCount, so it keeps the data alive.
2373            let r = b.downcast_ref::<u8>().unwrap();
2374            assert_eq!(*r, 5);
2375            assert_eq!(a.get_ref_count(), 3);
2376        }
2377        assert_eq!(a.get_ref_count(), 2);
2378
2379        {
2380            let m = b.downcast_mut::<u8>().unwrap();
2381            assert_eq!(*m, 5);
2382            assert_eq!(a.get_ref_count(), 3);
2383        }
2384        assert_eq!(a.get_ref_count(), 2);
2385
2386        drop(b);
2387        assert_eq!(a.get_ref_count(), 1);
2388        assert_eq!(*a.downcast_ref::<u8>().unwrap(), 5);
2389    }
2390
2391    #[test]
2392    fn debug_snapshot_matches_the_live_counters() {
2393        let a = RefAny::new(0x1122_3344u32);
2394        let d = a.sharing_info.debug_get_refcount_copied();
2395        assert_eq!(d.num_copies, 1);
2396        assert_eq!(d.num_refs, 0);
2397        assert_eq!(d.num_mutable_refs, 0);
2398        assert_eq!(d._internal_len, 4);
2399        assert_eq!(d._internal_layout_size, 4);
2400        assert_eq!(d._internal_layout_align, core::mem::align_of::<u32>());
2401        assert_eq!(d.type_id, RefAny::get_type_id_static::<u32>());
2402        assert_eq!(d.type_name.as_str(), "u32");
2403        assert_ne!(d.custom_destructor, 0);
2404        assert_eq!(d.serialize_fn, 0);
2405        assert_eq!(d.deserialize_fn, 0);
2406
2407        a.sharing_info.increase_ref();
2408        a.sharing_info.increase_refmut();
2409        let d2 = a.sharing_info.debug_get_refcount_copied();
2410        assert_eq!(d2.num_refs, 1);
2411        assert_eq!(d2.num_mutable_refs, 1);
2412        // The first snapshot is a copy, not a view: it must not have changed.
2413        assert_eq!(d.num_refs, 0);
2414
2415        a.sharing_info.decrease_ref();
2416        a.sharing_info.decrease_refmut();
2417        let d3 = a.sharing_info.debug_get_refcount_copied();
2418        assert_eq!((d3.num_refs, d3.num_mutable_refs), (0, 0));
2419
2420        // The Debug impl goes through `downcast()` — it must not panic.
2421        assert!(!alloc::format!("{:?}", a.sharing_info).is_empty());
2422    }
2423
2424    #[test]
2425    fn get_type_name_reports_the_rust_type() {
2426        #[derive(Clone)]
2427        struct AutotestNamed(#[allow(dead_code)] u8);
2428
2429        let a = RefAny::new(AutotestNamed(1));
2430        let name = a.get_type_name();
2431        assert!(
2432            name.as_str().contains("AutotestNamed"),
2433            "unexpected type name: {}",
2434            name.as_str()
2435        );
2436
2437        let generic = RefAny::new(Vec::<String>::new());
2438        assert!(generic.get_type_name().as_str().contains("Vec"));
2439
2440        assert_eq!(RefAny::new(1u32).get_type_name().as_str(), "u32");
2441    }
2442
2443    // ---- RefCount: construction, downcast, clone/drop balance ----
2444
2445    #[test]
2446    fn refcount_new_downcast_and_clone_lifecycle() {
2447        let rc = RefCount::new(RefCountInner {
2448            _internal_ptr: core::ptr::null(),
2449            num_copies: AtomicUsize::new(1),
2450            num_refs: AtomicUsize::new(0),
2451            num_mutable_refs: AtomicUsize::new(0),
2452            _internal_len: 0,
2453            _internal_layout_size: 0,
2454            _internal_layout_align: 1,
2455            type_id: 0xDEAD_BEEF,
2456            type_name: AzString::from_const_str("autotest::Synthetic"),
2457            custom_destructor: noop_destructor,
2458            serialize_fn: 0,
2459            deserialize_fn: 0,
2460            update_fn: 0,
2461        });
2462        assert!(!rc.ptr.is_null());
2463        assert!(rc.run_destructor);
2464
2465        let inner = rc.downcast();
2466        assert_eq!(inner.type_id, 0xDEAD_BEEF);
2467        assert_eq!(inner.type_name.as_str(), "autotest::Synthetic");
2468        assert_eq!(inner._internal_len, 0);
2469        assert!(rc.can_be_shared());
2470        assert!(rc.can_be_shared_mut());
2471
2472        // Clones must keep the boxed inner alive; the counters must return to 1
2473        // so the final drop frees it exactly once.
2474        let c1 = rc.clone();
2475        assert_eq!(rc.debug_get_refcount_copied().num_copies, 2);
2476        let c2 = c1.clone();
2477        assert_eq!(rc.debug_get_refcount_copied().num_copies, 3);
2478        drop(c2);
2479        drop(c1);
2480        assert_eq!(rc.debug_get_refcount_copied().num_copies, 1);
2481    }
2482
2483    // The borrow counters must saturate at 0 instead of wrapping to usize::MAX
2484    // (an unmatched `FooRef_delete` from C would otherwise permanently wedge the
2485    // runtime borrow checker), and stay usable afterwards.
2486    #[test]
2487    fn borrow_counters_saturate_at_zero_and_stay_usable() {
2488        let mut a = RefAny::new(3i64);
2489        {
2490            let rc = &a.sharing_info;
2491
2492            // 64 unmatched decrements on both counters.
2493            for _ in 0..64 {
2494                rc.decrease_ref();
2495                rc.decrease_refmut();
2496            }
2497            let d = rc.debug_get_refcount_copied();
2498            assert_eq!(d.num_refs, 0);
2499            assert_eq!(d.num_mutable_refs, 0);
2500            assert!(rc.can_be_shared());
2501            assert!(rc.can_be_shared_mut());
2502
2503            // Many shared borrows coexist, but block a mutable one.
2504            for _ in 0..256 {
2505                rc.increase_ref();
2506            }
2507            assert_eq!(rc.debug_get_refcount_copied().num_refs, 256);
2508            assert!(rc.can_be_shared());
2509            assert!(!rc.can_be_shared_mut());
2510            for _ in 0..256 {
2511                rc.decrease_ref();
2512            }
2513            assert_eq!(rc.debug_get_refcount_copied().num_refs, 0);
2514            assert!(rc.can_be_shared_mut());
2515
2516            // Same for the mutable counter, plus one extra decrement.
2517            rc.increase_refmut();
2518            rc.increase_refmut();
2519            assert!(!rc.can_be_shared());
2520            rc.decrease_refmut();
2521            rc.decrease_refmut();
2522            rc.decrease_refmut();
2523            assert_eq!(rc.debug_get_refcount_copied().num_mutable_refs, 0);
2524        }
2525
2526        // The borrow checker still works after all those underflow attempts.
2527        assert_eq!(*a.downcast_ref::<i64>().unwrap(), 3);
2528        assert!(a.downcast_mut::<i64>().is_some());
2529    }
2530
2531    // ---- get_type_id_static ----
2532
2533    // The u64 type ID is the ONLY runtime guard against a wrong-type downcast,
2534    // so distinct types must not collide (this is what folding ALL TypeId bytes
2535    // buys us) and it must be stable within a process run.
2536    #[test]
2537    fn type_id_static_is_stable_and_collision_free() {
2538        let ids = [
2539            RefAny::get_type_id_static::<u8>(),
2540            RefAny::get_type_id_static::<u16>(),
2541            RefAny::get_type_id_static::<u32>(),
2542            RefAny::get_type_id_static::<u64>(),
2543            RefAny::get_type_id_static::<u128>(),
2544            RefAny::get_type_id_static::<usize>(),
2545            RefAny::get_type_id_static::<i8>(),
2546            RefAny::get_type_id_static::<i16>(),
2547            RefAny::get_type_id_static::<i32>(),
2548            RefAny::get_type_id_static::<i64>(),
2549            RefAny::get_type_id_static::<i128>(),
2550            RefAny::get_type_id_static::<isize>(),
2551            RefAny::get_type_id_static::<f32>(),
2552            RefAny::get_type_id_static::<f64>(),
2553            RefAny::get_type_id_static::<bool>(),
2554            RefAny::get_type_id_static::<char>(),
2555            RefAny::get_type_id_static::<()>(),
2556            RefAny::get_type_id_static::<String>(),
2557            RefAny::get_type_id_static::<Vec<u8>>(),
2558            RefAny::get_type_id_static::<Vec<u16>>(),
2559            RefAny::get_type_id_static::<[u8; 1]>(),
2560            RefAny::get_type_id_static::<[u8; 2]>(),
2561            RefAny::get_type_id_static::<(u8, u8)>(),
2562            RefAny::get_type_id_static::<(u8, u16)>(),
2563            RefAny::get_type_id_static::<Option<u8>>(),
2564            RefAny::get_type_id_static::<Option<u16>>(),
2565        ];
2566
2567        for i in 0..ids.len() {
2568            for j in (i + 1)..ids.len() {
2569                assert_ne!(ids[i], ids[j], "type id collision between {i} and {j}");
2570            }
2571        }
2572
2573        // Deterministic within a run.
2574        assert_eq!(RefAny::get_type_id_static::<Vec<u8>>(), ids[18]);
2575        assert_eq!(RefAny::get_type_id_static::<u8>(), ids[0]);
2576    }
2577
2578    // ---- clone / instance ids ----
2579
2580    #[test]
2581    fn root_instance_id_is_zero_and_clones_are_distinct() {
2582        let a = RefAny::new(0u8);
2583        assert_eq!(a.instance_id, 0);
2584
2585        let b = a.clone();
2586        let c = b.clone();
2587        assert_ne!(b.instance_id, 0);
2588        assert_ne!(c.instance_id, 0);
2589        assert_ne!(b.instance_id, c.instance_id);
2590        assert_eq!(a.get_ref_count(), 3);
2591    }
2592
2593    // ---- replace_contents ----
2594
2595    #[test]
2596    fn replace_contents_zst_and_value_transitions() {
2597        #[derive(Clone)]
2598        struct Zst;
2599
2600        let mut a = RefAny::new(Zst);
2601        assert_eq!(a.get_data_len(), 0);
2602        assert!(a.get_data_ptr().is_null());
2603
2604        // ZST -> sized: a real allocation must appear.
2605        assert!(a.replace_contents(RefAny::new(0x4142_4344u32)));
2606        assert_eq!(a.get_data_len(), 4);
2607        assert!(!a.get_data_ptr().is_null());
2608        assert!(a.is_type(RefAny::get_type_id_static::<u32>()));
2609        assert_eq!(*a.downcast_ref::<u32>().unwrap(), 0x4142_4344);
2610
2611        // sized -> ZST: the pointer goes back to null and downcasts must fail
2612        // safely (releasing the borrow slot they speculatively took).
2613        assert!(a.replace_contents(RefAny::new(Zst)));
2614        assert_eq!(a.get_data_len(), 0);
2615        assert!(a.get_data_ptr().is_null());
2616        assert!(a.downcast_ref::<Zst>().is_none());
2617        assert!(a.downcast_mut::<Zst>().is_none());
2618        assert!(a.sharing_info.can_be_shared_mut());
2619    }
2620
2621    #[test]
2622    fn replace_contents_is_visible_to_all_clones() {
2623        let mut a = RefAny::new(1u32);
2624        let mut b = a.clone();
2625
2626        assert!(a.replace_contents(RefAny::new(2u32)));
2627        assert_eq!(*b.downcast_ref::<u32>().unwrap(), 2);
2628
2629        // The type may change too — every clone sees the new type.
2630        assert!(a.replace_contents(RefAny::new(String::from("swapped"))));
2631        assert!(b.downcast_ref::<u32>().is_none());
2632        assert_eq!(b.downcast_ref::<String>().unwrap().as_str(), "swapped");
2633        assert!(b.get_type_name().as_str().contains("String"));
2634        assert_eq!(b.get_type_id(), RefAny::get_type_id_static::<String>());
2635    }
2636
2637    #[test]
2638    fn replace_contents_denied_while_mutably_borrowed() {
2639        let mut a = RefAny::new(1u32);
2640        let mut b = a.clone();
2641
2642        let m = a.downcast_mut::<u32>().unwrap();
2643        // A live mutable borrow on the shared inner must block the replacement
2644        // (performing it would free memory the `RefMut` still points at).
2645        assert!(!b.replace_contents(RefAny::new(2u32)));
2646        drop(m);
2647
2648        assert!(b.replace_contents(RefAny::new(2u32)));
2649        assert_eq!(*b.downcast_ref::<u32>().unwrap(), 2);
2650    }
2651
2652    // The serialize/deserialize/update hooks are part of the replaced metadata:
2653    // after a replacement they describe the NEW value, not the old one.
2654    #[test]
2655    fn replace_contents_resets_the_fn_pointers_to_the_new_value() {
2656        let mut a = RefAny::new(1u32);
2657        a.set_serialize_fn(3);
2658        a.set_deserialize_fn(4);
2659        assert!(a.can_serialize());
2660        assert!(a.can_deserialize());
2661
2662        assert!(a.replace_contents(RefAny::new(2u32)));
2663        assert_eq!(a.get_serialize_fn(), 0);
2664        assert_eq!(a.get_deserialize_fn(), 0);
2665        assert_eq!(a.get_update_fn(), 0);
2666        assert!(!a.can_serialize());
2667        assert!(!a.can_deserialize());
2668    }
2669
2670    // Repeated replacement across changing sizes/alignments must neither leak nor
2671    // corrupt the payload (Miri checks the alloc/dealloc balance here).
2672    #[test]
2673    fn repeated_replace_contents_stays_consistent() {
2674        let mut a = RefAny::new(String::from("start"));
2675        for i in 0..16u32 {
2676            assert!(a.replace_contents(RefAny::new(i)));
2677            assert_eq!(*a.downcast_ref::<u32>().unwrap(), i);
2678            assert!(a.replace_contents(RefAny::new(u128::from(i) | (1 << 100))));
2679            assert_eq!(
2680                *a.downcast_ref::<u128>().unwrap(),
2681                u128::from(i) | (1 << 100)
2682            );
2683            assert!(a.replace_contents(RefAny::new(String::from("s"))));
2684        }
2685        assert_eq!(a.downcast_ref::<String>().unwrap().as_str(), "s");
2686    }
2687
2688    // ---- destructor robustness / concurrency ----
2689
2690    // `default_custom_destructor` is `extern "C"`: a panic from the payload's
2691    // `Drop` must be caught there, not unwound across the FFI boundary (UB).
2692    #[cfg(feature = "std")]
2693    #[test]
2694    fn panicking_payload_drop_is_contained() {
2695        struct PanicOnDrop(#[allow(dead_code)] u64);
2696        impl Drop for PanicOnDrop {
2697            fn drop(&mut self) {
2698                panic!("autotest: payload Drop panicked (expected, must be contained)");
2699            }
2700        }
2701
2702        let a = RefAny::new(PanicOnDrop(1));
2703        drop(a); // must not propagate the panic out of the extern "C" destructor
2704    }
2705
2706    // RefAny is Send + Sync: concurrent clone/borrow/drop from several threads
2707    // must leave the reference count exactly where it started.
2708    #[cfg(feature = "std")]
2709    #[test]
2710    fn concurrent_clone_and_borrow_keeps_the_refcount_balanced() {
2711        use std::{sync::Arc, thread};
2712
2713        let shared = Arc::new(RefAny::new(11u32));
2714        let mut handles = Vec::new();
2715
2716        for _ in 0..4 {
2717            let s = Arc::clone(&shared);
2718            handles.push(thread::spawn(move || {
2719                for _ in 0..16 {
2720                    let mut local = (*s).clone();
2721                    // No thread takes a mutable borrow, so a shared borrow can
2722                    // never be denied.
2723                    let r = local
2724                        .downcast_ref::<u32>()
2725                        .expect("shared borrow must always succeed here");
2726                    assert_eq!(*r, 11);
2727                }
2728            }));
2729        }
2730        for h in handles {
2731            h.join().expect("worker thread panicked");
2732        }
2733
2734        assert_eq!(shared.get_ref_count(), 1);
2735    }
2736}