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

            
32
use alloc::{boxed::Box, string::String};
33
use core::{
34
    alloc::Layout,
35
    ffi::c_void,
36
    fmt,
37
    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
38
};
39

            
40
use azul_css::AzString;
41

            
42
/// C-compatible destructor function type for `RefAny`.
43
/// Called when the last reference to a `RefAny` is dropped.
44
pub type RefAnyDestructorType = extern "C" fn(*mut c_void);
45

            
46
// NOTE: JSON serialization/deserialization callback types are defined in azul_layout::json
47
// The actual types are:
48
//   RefAnySerializeFnType = extern "C" fn(RefAny) -> Json
49
//   RefAnyDeserializeFnType = extern "C" fn(Json) -> ResultRefAnyString
50
// In azul_core, we only store function pointers as usize (0 = not set).
51

            
52
/// Internal reference counting metadata for `RefAny`.
53
///
54
/// This struct tracks:
55
///
56
/// - How many `RefAny` clones exist (`num_copies`)
57
/// - How many shared borrows are active (`num_refs`)
58
/// - How many mutable borrows are active (`num_mutable_refs`)
59
/// - Memory layout information for correct deallocation
60
/// - Type information for runtime type checking
61
///
62
/// # Thread Safety
63
///
64
/// All counters are `AtomicUsize` with `SeqCst` ordering, making them safe to access
65
/// from multiple threads simultaneously. The strong ordering ensures no thread can
66
/// observe inconsistent states (e.g., both seeing count=1 during final drop).
67
#[derive(Debug)]
68
#[repr(C)]
69
// `_internal_*` are C-ABI field names exposed in api.json; the `_` prefix is the
70
// intentional "internal" convention and cannot be renamed without breaking the ABI.
71
#[allow(clippy::pub_underscore_fields)]
72
pub struct RefCountInner {
73
    /// Type-erased pointer to heap-allocated data.
74
    ///
75
    /// SAFETY: Must be properly aligned for the stored type (guaranteed by
76
    /// `Layout::from_size_align` in `new_c`). Never null for non-ZST types.
77
    ///
78
    /// This pointer is shared by all `RefAny` clones, so `replace_contents`
79
    /// updates are visible to all clones.
80
    pub _internal_ptr: *const c_void,
81

            
82
    /// Number of `RefAny` instances sharing the same data.
83
    /// When this reaches 0, the data is deallocated.
84
    pub num_copies: AtomicUsize,
85

            
86
    /// Number of active shared borrows (`Ref<T>`).
87
    /// While > 0, mutable borrows are forbidden.
88
    pub num_refs: AtomicUsize,
89

            
90
    /// Number of active mutable borrows (`RefMut<T>`).
91
    /// While > 0, all other borrows are forbidden.
92
    pub num_mutable_refs: AtomicUsize,
93

            
94
    /// Size of the stored type in bytes (from `size_of::<T>()`).
95
    pub _internal_len: usize,
96

            
97
    /// Layout size for deallocation (from `Layout::size()`).
98
    pub _internal_layout_size: usize,
99

            
100
    /// Required alignment for the stored type (from `align_of::<T>()`).
101
    /// CRITICAL: Must match the alignment used during allocation to prevent UB.
102
    pub _internal_layout_align: usize,
103

            
104
    /// Runtime type identifier computed from `TypeId::of::<T>()`.
105
    /// Used to prevent invalid downcasts.
106
    pub type_id: u64,
107

            
108
    /// Human-readable type name (e.g., "`MyStruct`") for debugging.
109
    pub type_name: AzString,
110

            
111
    /// Function pointer to correctly drop the type-erased data.
112
    /// SAFETY: Must be called with a pointer to data of the correct type.
113
    pub custom_destructor: extern "C" fn(*mut c_void),
114

            
115
    /// Function pointer to serialize `RefAny` to JSON (0 = not set).
116
    /// Cast to `RefAnySerializeFnType` (defined in `azul_layout::json`) when called.
117
    /// Type: extern "C" fn(RefAny) -> Json
118
    pub serialize_fn: usize,
119

            
120
    /// Function pointer to deserialize JSON to new `RefAny` (0 = not set).
121
    /// Cast to `RefAnyDeserializeFnType` (defined in `azul_layout::json`) when called.
122
    /// Type: extern "C" fn(Json) -> `ResultRefAnyString`
123
    pub deserialize_fn: usize,
124

            
125
    /// Function pointer to an on-update observer (0 = not set).
126
    /// Cast to `extern "C" fn(*const c_void, usize)` — the (data ptr, byte len)
127
    /// of the *pre-mutation* data — and fired from `downcast_mut` BEFORE the
128
    /// mutable borrow is handed out. This is the foundation for undo/redo
129
    /// snapshots and client/server state sync. Set via `RefAny::set_update_fn`.
130
    pub update_fn: usize,
131
}
132

            
133
/// Wrapper around a heap-allocated `RefCountInner`.
134
///
135
/// This is the shared metadata that all `RefAny` clones point to.
136
/// The `RefCount` is responsible for all memory management:
137
///
138
/// - `RefCount::clone()` increments `num_copies` in `RefCountInner`
139
/// - `RefCount::drop()` decrements `num_copies` and, if it reaches 0:
140
///   1. Frees the `RefCountInner`
141
///   2. Calls the custom destructor on the data
142
///   3. Deallocates the data memory
143
///
144
/// # Why `run_destructor: bool`
145
///
146
/// This flag tracks whether this `RefCount` instance should decrement
147
/// `num_copies` when dropped. Set to `true` for all clones (including
148
/// those created by `RefAny::clone()` and `AZ_REFLECT` macros).
149
/// Set to `false` after the decrement has been performed to prevent
150
/// double-decrement.
151
#[derive(Hash, PartialEq, PartialOrd, Ord, Eq)]
152
#[repr(C)]
153
pub struct RefCount {
154
    pub ptr: *const RefCountInner,
155
    pub run_destructor: bool,
156
}
157

            
158
impl fmt::Debug for RefCount {
159
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160
1
        self.downcast().fmt(f)
161
1
    }
162
}
163

            
164
impl Clone for RefCount {
165
    /// Clones the `RefCount` and increments the reference count.
166
    ///
167
    /// # Safety
168
    ///
169
    /// This is safe because:
170
    /// - The ptr is valid (created from `Box::into_raw`)
171
    /// - `num_copies` is atomically incremented with `SeqCst` ordering
172
    /// - This ensures the `RefCountInner` is not freed while clones exist
173
177377
    fn clone(&self) -> Self {
174
        // CRITICAL: Must increment num_copies so the RefCountInner is not freed
175
        // while this clone exists. The C macros (AZ_REFLECT) use AzRefCount_clone
176
        // to create Ref/RefMut guards, and those guards must keep the data alive.
177
177377
        if !self.ptr.is_null() {
178
            // SAFETY: `ptr` is non-null (checked) and came from `Box::into_raw`
179
            // in `RefCount::new`; it stays alive as long as any clone exists
180
            // because every clone increments `num_copies` here.
181
177377
            unsafe {
182
177377
                (*self.ptr).num_copies.fetch_add(1, AtomicOrdering::SeqCst);
183
177377
            }
184
        }
185
177377
        Self {
186
177377
            ptr: self.ptr,
187
177377
            run_destructor: true,
188
177377
        }
189
177377
    }
190
}
191

            
192
impl Drop for RefCount {
193
    /// Decrements the reference count when a `RefCount` clone is dropped.
194
    ///
195
    /// If this was the last reference (`num_copies` reaches 0), this will also
196
    /// free the `RefCountInner` and call the custom destructor.
197
    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json
198
                                              // naming convention; internal access is required
199
1356104
    fn drop(&mut self) {
200
        // Only decrement if run_destructor is true (meaning this is a clone)
201
        // and the pointer is valid
202
1356104
        if !self.run_destructor || self.ptr.is_null() {
203
1
            return;
204
1356103
        }
205
1356103
        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
1356103
        let inner = self.ptr;
218
1356103
        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
1356103
        let current_copies = unsafe {
228
1356103
            match (*inner).num_copies.fetch_update(
229
1356103
                AtomicOrdering::SeqCst,
230
1356103
                AtomicOrdering::SeqCst,
231
1356103
                |n| n.checked_sub(1),
232
            ) {
233
1356103
                Ok(prev) => prev,
234
                Err(_zero) => return,
235
            }
236
        };
237

            
238
        // If previous value wasn't 1, other references still exist
239
1356103
        if current_copies != 1 {
240
1050995
            return;
241
305108
        }
242

            
243
        // We're the last reference! Clean up.
244
        // SAFETY: ptr came from Box::into_raw, and we're the last reference
245
305108
        let sharing_info = unsafe { Box::from_raw(inner.cast_mut()) };
246
305108
        let sharing_info = *sharing_info; // Box deallocates RefCountInner here
247

            
248
        // Get the data pointer
249
305108
        let data_ptr = sharing_info._internal_ptr;
250

            
251
        // Handle zero-sized types specially
252
305108
        if sharing_info._internal_len == 0
253
292566
            || sharing_info._internal_layout_size == 0
254
292566
            || data_ptr.is_null()
255
12542
        {
256
12542
            let mut _dummy: [u8; 0] = [];
257
12542
            // Call destructor even for ZSTs (may have side effects)
258
12542
            (sharing_info.custom_destructor)(_dummy.as_mut_ptr().cast::<c_void>());
259
12542
        } 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
292566
            let layout = Layout::from_size_align(
266
292566
                sharing_info._internal_layout_size,
267
292566
                sharing_info._internal_layout_align,
268
            )
269
292566
            .expect("RefCount::drop: stored layout was invalid");
270

            
271
            // Phase 1: Run the custom destructor
272
292566
            (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
292566
            unsafe {
279
292566
                alloc::alloc::dealloc(data_ptr as *mut u8, layout);
280
292566
            }
281
        }
282
1356104
    }
283
}
284

            
285
/// Debug-friendly snapshot of `RefCountInner` with non-atomic values.
286
#[derive(Debug, Clone)]
287
pub(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

            
303
/// Say ONCE, on stderr, that something borrowed a released `RefAny`.
304
///
305
/// Returning `None` keeps the process alive, but a callback whose data has been
306
/// released silently does nothing, which is its own kind of bug — so the first
307
/// occurrence is announced rather than swallowed. Once per process: this can
308
/// fire from a hot path (every callback dispatch downcasts), and a per-frame
309
/// warning would be its own denial of service. `RUST_BACKTRACE=1` on the run
310
/// that prints it names the caller.
311
#[cfg(feature = "std")]
312
3
fn report_released_downcast() {
313
    use std::sync::atomic::{AtomicBool, Ordering};
314
    static SAID: AtomicBool = AtomicBool::new(false);
315
3
    if !SAID.swap(true, Ordering::Relaxed) {
316
1
        eprintln!(
317
1
            "[azul][refany] a RELEASED RefAny was downcast: its RefCount is already freed, so the \
318
1
             borrow returned None and whatever wanted the data did nothing. This is a \
319
1
             use-after-release in the CALLER, not here. Re-run with RUST_BACKTRACE=1 to name it. \
320
1
             (said once per process)"
321
        );
322
1
        if std::env::var("RUST_BACKTRACE").is_ok() {
323
            eprintln!("{}", std::backtrace::Backtrace::force_capture());
324
1
        }
325
2
    }
326
3
}
327

            
328
#[cfg(not(feature = "std"))]
329
const fn report_released_downcast() {}
330

            
331
impl RefCount {
332
    /// Creates a new `RefCount` by boxing the metadata on the heap.
333
    ///
334
    /// # Safety
335
    ///
336
    /// Safe because we're creating a new allocation with `Box::new`,
337
    /// then immediately leaking it with `into_raw` to get a stable pointer.
338
305252
    fn new(ref_count: RefCountInner) -> Self {
339
305252
        Self {
340
305252
            ptr: Box::into_raw(Box::new(ref_count)),
341
305252
            run_destructor: true,
342
305252
        }
343
305252
    }
344

            
345
    /// Has this `RefCount`'s metadata already been released?
346
    ///
347
    /// A null `ptr` is a REAL state, not corruption: [`Drop`] nulls the field
348
    /// after freeing the `RefCountInner`, deliberately mirroring the `ptr = 0`
349
    /// convention the `AZ_REFLECT` C macros use, so that a second
350
    /// `AzRefCount_delete` of the same C-owned struct is a no-op instead of a
351
    /// double free. Anything reachable from SAFE Rust must therefore treat a
352
    /// released `RefCount` as "no data", not as a reason to abort — see
353
    /// [`RefAny::get_type_id`].
354
370934
    pub(crate) const fn is_released(&self) -> bool {
355
370934
        self.ptr.is_null()
356
370934
    }
357

            
358
    /// Dereferences the raw pointer to access the metadata.
359
    ///
360
    /// # Safety
361
    ///
362
    /// Safe because:
363
    /// - The pointer is created from `Box::into_raw`, so it's valid and properly aligned
364
    /// - The lifetime is tied to `&self`, ensuring the pointer is still alive
365
    /// - Reference counting ensures the data isn't freed while references exist
366
1662119
    fn downcast(&self) -> &RefCountInner {
367
1662119
        assert!(
368
1662119
            !self.ptr.is_null(),
369
            "[RefCount::downcast] FATAL: self.ptr is null!"
370
        );
371
        // SAFETY: `ptr` is non-null (asserted) and came from `Box::into_raw`; the
372
        // returned reference is bounded by `&self`, and refcounting keeps the
373
        // `RefCountInner` alive for at least that long.
374
1662119
        unsafe { &*self.ptr }
375
1662119
    }
376

            
377
    /// Creates a debug snapshot of the current reference counts.
378
    ///
379
    /// Loads all atomic values with `SeqCst` ordering to get a consistent view.
380
    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json
381
                                              // naming convention; internal access is required
382
35
    pub(crate) fn debug_get_refcount_copied(&self) -> RefCountInnerDebug {
383
35
        let dc = self.downcast();
384
35
        RefCountInnerDebug {
385
35
            num_copies: dc.num_copies.load(AtomicOrdering::SeqCst),
386
35
            num_refs: dc.num_refs.load(AtomicOrdering::SeqCst),
387
35
            num_mutable_refs: dc.num_mutable_refs.load(AtomicOrdering::SeqCst),
388
35
            _internal_len: dc._internal_len,
389
35
            _internal_layout_size: dc._internal_layout_size,
390
35
            _internal_layout_align: dc._internal_layout_align,
391
35
            type_id: dc.type_id,
392
35
            type_name: dc.type_name.clone(),
393
35
            custom_destructor: dc.custom_destructor as usize,
394
35
            serialize_fn: dc.serialize_fn,
395
35
            deserialize_fn: dc.deserialize_fn,
396
35
        }
397
35
    }
398

            
399
    /// Runtime check: can we create a shared borrow?
400
    ///
401
    /// Returns `true` if there are no active mutable borrows.
402
    /// Multiple shared borrows can coexist (like `&T` in Rust).
403
    ///
404
    /// # Memory Ordering
405
    ///
406
    /// Uses `SeqCst` to ensure we see the most recent state from all threads.
407
    /// If another thread just released a mutable borrow, we'll see it.
408
    #[must_use]
409
121522
    pub fn can_be_shared(&self) -> bool {
410
121522
        self.downcast()
411
121522
            .num_mutable_refs
412
121522
            .load(AtomicOrdering::SeqCst)
413
121522
            == 0
414
121522
    }
415

            
416
    /// Runtime check: can we create a mutable borrow?
417
    ///
418
    /// Returns `true` only if there are ZERO active borrows of any kind.
419
    /// This enforces Rust's exclusive mutability rule (like `&mut T`).
420
    ///
421
    /// # Memory Ordering
422
    ///
423
    /// Uses `SeqCst` to ensure we see all recent borrows from all threads.
424
    /// Both counters must be checked atomically to prevent races.
425
    #[must_use]
426
14
    pub fn can_be_shared_mut(&self) -> bool {
427
14
        let info = self.downcast();
428
14
        info.num_mutable_refs.load(AtomicOrdering::SeqCst) == 0
429
13
            && info.num_refs.load(AtomicOrdering::SeqCst) == 0
430
14
    }
431

            
432
    /// Increments the shared borrow counter.
433
    ///
434
    /// Called when a `Ref<T>` is created. The `Ref::drop` will decrement it.
435
    ///
436
    /// # Memory Ordering
437
    ///
438
    /// `SeqCst` ensures this increment is visible to all threads before they
439
    /// try to acquire a mutable borrow (which checks this counter).
440
121771
    pub fn increase_ref(&self) {
441
121771
        self.downcast()
442
121771
            .num_refs
443
121771
            .fetch_add(1, AtomicOrdering::SeqCst);
444
121771
    }
445

            
446
    /// Decrements the shared borrow counter.
447
    ///
448
    /// Called when a `Ref<T>` is dropped, indicating the borrow is released.
449
    ///
450
    /// # Underflow guard
451
    ///
452
    /// Saturates at 0: an unmatched decrement — e.g. a C caller running
453
    /// `FooRef_delete` after a FAILED downcast with a pre-0.2.1 copy of
454
    /// `azul.h` (whose macro did not skip the decrease), or a plain
455
    /// double-delete — must not wrap `num_refs` to `usize::MAX`, which
456
    /// would make `can_be_shared_mut()` return `false` for the rest of
457
    /// the process (callbacks silently stop mutating state).
458
    ///
459
    /// # Memory Ordering
460
    ///
461
    /// `SeqCst` ensures this decrement is immediately visible to other threads
462
    /// waiting to acquire a mutable borrow.
463
121836
    pub fn decrease_ref(&self) {
464
121836
        let _ = self.downcast().num_refs.fetch_update(
465
121836
            AtomicOrdering::SeqCst,
466
121836
            AtomicOrdering::SeqCst,
467
121836
            |n| n.checked_sub(1),
468
        );
469
121836
    }
470

            
471
    /// Increments the mutable borrow counter.
472
    ///
473
    /// Called when a `RefMut<T>` is created. Should only succeed when this
474
    /// counter and `num_refs` are both 0.
475
    ///
476
    /// # Memory Ordering
477
    ///
478
    /// `SeqCst` ensures this increment is visible to all other threads,
479
    /// blocking them from acquiring any borrow (shared or mutable).
480
4
    pub fn increase_refmut(&self) {
481
4
        self.downcast()
482
4
            .num_mutable_refs
483
4
            .fetch_add(1, AtomicOrdering::SeqCst);
484
4
    }
485

            
486
    /// Decrements the mutable borrow counter.
487
    ///
488
    /// Called when a `RefMut<T>` is dropped, releasing exclusive access.
489
    ///
490
    /// # Underflow guard
491
    ///
492
    /// Saturates at 0 (see [`Self::decrease_ref`]): a double
493
    /// `FooRefMut_delete` from C must not wrap `num_mutable_refs`, which
494
    /// would corrupt the runtime borrow checker and let a second thread
495
    /// or timer callback obtain an aliasing mutable borrow.
496
    ///
497
    /// # Memory Ordering
498
    ///
499
    /// `SeqCst` ensures this decrement is immediately visible, allowing
500
    /// other threads to acquire borrows.
501
56027
    pub fn decrease_refmut(&self) {
502
56027
        let _ = self.downcast().num_mutable_refs.fetch_update(
503
56027
            AtomicOrdering::SeqCst,
504
56027
            AtomicOrdering::SeqCst,
505
56027
            |n| n.checked_sub(1),
506
        );
507
56027
    }
508
}
509

            
510
/// RAII guard for a shared borrow of type `T` from a `RefAny`.
511
///
512
/// Similar to `std::cell::Ref`, this automatically decrements the borrow
513
/// counter when dropped, ensuring borrows are properly released.
514
///
515
/// # Deref
516
///
517
/// Implements `Deref<Target = T>` so you can use it like `&T`.
518
#[derive(Debug)]
519
#[repr(C)]
520
pub struct Ref<'a, T> {
521
    ptr: &'a T,
522
    sharing_info: RefCount,
523
}
524

            
525
impl<T> Drop for Ref<'_, T> {
526
    /// Automatically releases the shared borrow when the guard goes out of scope.
527
    ///
528
    /// # Safety
529
    ///
530
    /// Safe because `decrease_ref` uses atomic operations and is designed to be
531
    /// called exactly once per `Ref` instance.
532
11269
    fn drop(&mut self) {
533
11269
        self.sharing_info.decrease_ref();
534
11269
    }
535
}
536

            
537
impl<T> core::ops::Deref for Ref<'_, T> {
538
    type Target = T;
539

            
540
14138
    fn deref(&self) -> &Self::Target {
541
14138
        self.ptr
542
14138
    }
543
}
544

            
545
/// RAII guard for a mutable borrow of type `T` from a `RefAny`.
546
///
547
/// Similar to `std::cell::RefMut`, this automatically decrements the mutable
548
/// borrow counter when dropped, releasing exclusive access.
549
///
550
/// # Deref / `DerefMut`
551
///
552
/// Implements both `Deref` and `DerefMut` so you can use it like `&mut T`.
553
#[derive(Debug)]
554
#[repr(C)]
555
pub struct RefMut<'a, T> {
556
    ptr: &'a mut T,
557
    sharing_info: RefCount,
558
}
559

            
560
impl<T> Drop for RefMut<'_, T> {
561
    /// Automatically releases the mutable borrow when the guard goes out of scope.
562
    ///
563
    /// # Safety
564
    ///
565
    /// Safe because `decrease_refmut` uses atomic operations and is designed to be
566
    /// called exactly once per `RefMut` instance.
567
4839
    fn drop(&mut self) {
568
4839
        self.sharing_info.decrease_refmut();
569
4839
    }
570
}
571

            
572
impl<T> core::ops::Deref for RefMut<'_, T> {
573
    type Target = T;
574

            
575
27407
    fn deref(&self) -> &Self::Target {
576
27407
        &*self.ptr
577
27407
    }
578
}
579

            
580
impl<T> core::ops::DerefMut for RefMut<'_, T> {
581
20849
    fn deref_mut(&mut self) -> &mut Self::Target {
582
20849
        self.ptr
583
20849
    }
584
}
585

            
586
/// Type-erased, reference-counted smart pointer with runtime borrow checking.
587
///
588
/// `RefAny` is similar to `Arc<RefCell<dyn Any>>`, providing:
589
/// - Type erasure (stores any `'static` type)
590
/// - Reference counting (clones share the same data)
591
/// - Runtime borrow checking (enforces Rust's borrowing rules at runtime)
592
/// - FFI compatibility (`#[repr(C)]` and C-compatible API)
593
///
594
/// # Thread Safety
595
///
596
/// - `Send`: Can be moved between threads (heap-allocated data, atomic counters)
597
/// - `Sync`: Can be shared between threads (`downcast_ref/mut` require `&mut self`)
598
///
599
/// # Memory Safety
600
///
601
/// Fixed critical UB bugs in alignment, copy count, and pointer provenance.
602
/// All operations are verified with Miri to ensure absence of undefined behavior.
603
///
604
/// # Usage
605
///
606
/// ```rust
607
/// # use azul_core::refany::RefAny;
608
/// let data = RefAny::new(42i32);
609
/// let mut data_clone = data.clone(); // shares the same heap allocation
610
///
611
/// // Runtime-checked downcasting with type safety
612
/// if let Some(value_ref) = data_clone.downcast_ref::<i32>() {
613
///     assert_eq!(*value_ref, 42);
614
/// };
615
///
616
/// // Runtime-checked mutable borrowing
617
/// if let Some(mut value_mut) = data_clone.downcast_mut::<i32>() {
618
///     *value_mut = 100;
619
/// };
620
/// ```
621
#[derive(Debug)]
622
#[repr(C)]
623
pub struct RefAny {
624
    /// Shared metadata: reference counts, type info, destructor, AND data pointer.
625
    ///
626
    /// All `RefAny` clones point to the same `RefCountInner` via this field.
627
    /// The data pointer is stored in `RefCountInner` so all clones see the same
628
    /// pointer, even after `replace_contents()` is called.
629
    ///
630
    /// The `run_destructor` flag on `RefCount` controls whether dropping this
631
    /// `RefAny` should decrement the reference count and potentially free memory.
632
    pub sharing_info: RefCount,
633

            
634
    /// Unique ID for this specific clone (root = 0, subsequent clones increment).
635
    ///
636
    /// Used to distinguish between the original and clones for debugging.
637
    pub instance_id: u64,
638
}
639

            
640
// The comparison traits below are hand-written, NOT derived, and key on
641
// `sharing_info` ALONE. `instance_id` is deliberately omitted:
642
//
643
//     // self.instance_id == other.instance_id   <-- NEVER compare this
644
//
645
// `instance_id` is a debug-only counter that `clone()` increments (original = 0,
646
// first clone = 1, ...). Deriving equality folded it in, so a `RefAny` never
647
// equaled its own clone even though both point at the same `RefCountInner` — the
648
// same heap data, same refcount. Equality here means "same data", not "same
649
// handle"; `sharing_info` (a pointer + flag) already distinguishes unrelated
650
// instances.
651
//
652
// Hash/Ord must key on exactly the same fields as PartialEq or they break their
653
// own contracts (equal values must hash equally; `cmp() == Equal` must imply
654
// `==`), so all five delegate to `sharing_info`.
655
impl PartialEq for RefAny {
656
771
    fn eq(&self, other: &Self) -> bool {
657
771
        self.sharing_info == other.sharing_info
658
771
    }
659
}
660

            
661
impl Eq for RefAny {}
662

            
663
impl core::hash::Hash for RefAny {
664
162
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
665
162
        core::hash::Hash::hash(&self.sharing_info, state);
666
162
    }
667
}
668

            
669
impl PartialOrd for RefAny {
670
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
671
        Some(self.cmp(other))
672
    }
673
}
674

            
675
impl Ord for RefAny {
676
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
677
        self.sharing_info.cmp(&other.sharing_info)
678
    }
679
}
680

            
681
impl_option!(
682
    RefAny,
683
    OptionRefAny,
684
    copy = false,
685
    [Debug, Hash, Clone, PartialEq, PartialOrd, Ord, Eq]
686
);
687

            
688
// AUDIT: unsound-but-required. These `Send`/`Sync` impls are unconditional in
689
// `T`: a `!Send`/`!Sync` payload moved or shared cross-thread races its own
690
// internals. This is an INTENTIONAL FFI design constraint — `RefAny` is a
691
// type-erased C-ABI handle with no way to carry `T: Send + Sync` bounds across
692
// the boundary, and the framework's threading model keeps a given payload on
693
// one thread in practice. Left as-is per the audit; do not "fix" by adding
694
// bounds (it would break the erased FFI type).
695
//
696
// SAFETY: RefAny is Send because:
697
// - The data pointer points to heap memory (can be sent between threads)
698
// - All shared state (RefCountInner) uses atomic operations
699
// - No thread-local storage is used
700
#[allow(clippy::non_send_fields_in_send_ty)] // see SAFETY note above: atomic refcount, no TLS, no
701
                                             // cross-thread deref
702
unsafe impl Send for RefAny {}
703

            
704
// SAFETY: RefAny is Sync because:
705
// - Methods on `&RefAny` (like `clone`, `get_type_id`) only use atomic operations or read immutable
706
//   data, which is inherently thread-safe
707
// - The runtime borrow checker (via `can_be_shared/shared_mut`) uses SeqCst atomics
708
//
709
// AUDIT: unsound-but-required (same intentional FFI constraint as `Send` above).
710
//
711
// The check-then-increment race that this note described in `downcast_ref/mut`
712
// is now FIXED (both use atomic `fetch_add`+validate / `compare_exchange`
713
// acquisition — see those methods). The remaining unsoundness is only the
714
// unconditional-in-`T` `Sync`, which is required by the erased C-ABI type.
715
unsafe impl Sync for RefAny {}
716

            
717
impl RefAny {
718
    /// Creates a new type-erased `RefAny` containing the given value.
719
    ///
720
    /// This is the primary way to construct a `RefAny` from Rust code.
721
    ///
722
    /// # Type Safety
723
    ///
724
    /// Stores the `TypeId` of `T` for runtime type checking during downcasts.
725
    ///
726
    /// # Memory Layout
727
    ///
728
    /// - Allocates memory on the heap with correct size (`size_of::<T>()`) and alignment
729
    ///   (`align_of::<T>()`)
730
    /// - Copies the value into the heap allocation
731
    /// - Forgets the original value to prevent double-drop
732
    ///
733
    /// # Custom Destructor
734
    ///
735
    /// Creates a type-specific destructor that:
736
    /// 1. Copies the data from heap back to stack
737
    /// 2. Calls `mem::drop` to run `T`'s destructor
738
    /// 3. The heap memory is freed separately in `RefAny::drop`
739
    ///
740
    /// This two-phase destruction ensures proper cleanup even for complex types.
741
    ///
742
    /// # Safety
743
    ///
744
    /// Safe because:
745
    /// - `mem::forget` prevents double-drop of the original value
746
    /// - Type `T` and destructor `<U>` are matched at compile time
747
    /// - `ptr::copy_nonoverlapping` with count=1 copies exactly one `T`
748
    ///
749
    /// # Example
750
    ///
751
    /// ```rust
752
    /// # use azul_core::refany::RefAny;
753
    /// let mut data = RefAny::new(42i32);
754
    /// let value = data.downcast_ref::<i32>().unwrap();
755
    /// assert_eq!(*value, 42);
756
    /// ```
757
42121
    pub fn new<T: 'static>(value: T) -> Self {
758
        /// Type-specific destructor that properly drops the inner value.
759
        ///
760
        /// # Safety
761
        ///
762
        /// Safe to call ONLY with a pointer that was created by `RefAny::new<U>`.
763
        /// The type `U` must match the original type `T`.
764
        ///
765
        /// # Why Copy to Stack?
766
        ///
767
        /// Rust's drop glue expects a value, not a pointer. We copy the data
768
        /// to the stack so `mem::drop` can run the destructor properly.
769
        ///
770
        /// # Critical Fix
771
        ///
772
        /// The third argument to `copy_nonoverlapping` is the COUNT (1 element),
773
        /// not the SIZE in bytes. Using `size_of::<U>()` here would copy
774
        /// `size_of::<U>()` elements, causing buffer overflow.
775
42042
        extern "C" fn default_custom_destructor<U: 'static>(ptr: *mut c_void) {
776
            use core::{mem, ptr};
777

            
778
            // The actual drop glue. `U::drop` is arbitrary user code and this
779
            // function is `extern "C"` (called across the FFI boundary from the
780
            // C ABI teardown), so a panic escaping here would unwind across that
781
            // boundary = UB.
782
            // SAFETY: this fn is only installed by `RefAny::new::<U>`, so `ptr`
783
            // points to an initialized, properly aligned `U` that no other code
784
            // still references (we are in the final drop). We move it out exactly
785
            // once (`count = 1`) and run its drop glue.
786
42042
            let run = || unsafe {
787
                // A ZST has no bytes to move, and `ptr` is not a real pointer to one:
788
                // `RefAny::new` never allocates for a ZST, and `RefCount::drop`
789
                // substitutes a 1-byte-aligned dummy. Feeding that to
790
                // `copy_nonoverlapping` violates its "aligned and non-null"
791
                // precondition (`[u64; 0]` demands align 8) — UB, and Rust's debug
792
                // check turns it into a NON-UNWINDING abort that kills the process.
793
                //
794
                // A ZST has exactly one value, so conjure it directly and run its drop
795
                // glue without touching `ptr` at all.
796
42042
                if size_of::<U>() == 0 {
797
                    // Sound for a ZST (exactly one value, touches no memory); the
798
                    // size_of == 0 guard is what makes assume_init well-defined here.
799
                    #[allow(clippy::uninit_assumed_init)]
800
3244
                    drop(mem::MaybeUninit::<U>::uninit().assume_init());
801
3244
                    return;
802
38798
                }
803

            
804
                // Allocate uninitialized stack space for one `U`
805
38798
                let mut stack_mem = mem::MaybeUninit::<U>::uninit();
806

            
807
                // Copy 1 element of type U from heap to stack
808
38798
                ptr::copy_nonoverlapping(
809
38798
                    ptr as *const U,
810
38798
                    stack_mem.as_mut_ptr(),
811
                    1, // CRITICAL: This is element count, not byte count!
812
                );
813

            
814
                // Take ownership and run the destructor
815
38798
                let stack_mem = stack_mem.assume_init();
816
38798
                drop(stack_mem); // Runs U's Drop implementation
817
42042
            };
818

            
819
            // AUDIT: contain any panic from `U::drop` so it can't unwind across
820
            // the `extern "C"` boundary. `catch_unwind` needs `std`; `no_std`
821
            // builds use `panic = "abort"`, where unwinding cannot occur.
822
            #[cfg(feature = "std")]
823
42042
            {
824
42042
                drop(std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)));
825
42042
            }
826
            #[cfg(not(feature = "std"))]
827
            {
828
                run();
829
            }
830
42042
        }
831

            
832
42121
        let type_name = ::core::any::type_name::<T>();
833
42121
        let type_id = Self::get_type_id_static::<T>();
834

            
835
42121
        let st = AzString::from_const_str(type_name);
836
42121
        let s = Self::new_c(
837
42121
            (&raw const value) as *const c_void,
838
42121
            ::core::mem::size_of::<T>(),
839
42121
            ::core::mem::align_of::<T>(), // CRITICAL: Pass alignment to prevent UB
840
42121
            type_id,
841
42121
            st,
842
42121
            default_custom_destructor::<T>,
843
            0, // serialize_fn: not set for Rust types by default
844
            0, // deserialize_fn: not set for Rust types by default
845
        );
846
42121
        ::core::mem::forget(value); // Prevent double-drop
847
42121
        s
848
42121
    }
849

            
850
    /// C-ABI compatible function to create a `RefAny` from raw components.
851
    ///
852
    /// This is the low-level constructor used by FFI bindings (C, Python, etc.).
853
    ///
854
    /// # Parameters
855
    ///
856
    /// - `ptr`: Pointer to the value to store (will be copied)
857
    /// - `len`: Size of the value in bytes (`size_of::<T>()`)
858
    /// - `align`: Required alignment in bytes (`align_of::<T>()`)
859
    /// - `type_id`: Unique identifier for the type (for downcast safety)
860
    /// - `type_name`: Human-readable type name (for debugging)
861
    /// - `custom_destructor`: Function to call when the last reference is dropped
862
    /// - `serialize_fn`: Function pointer for JSON serialization (0 = not set)
863
    /// - `deserialize_fn`: Function pointer for JSON deserialization (0 = not set)
864
    ///
865
    /// # Safety
866
    ///
867
    /// Caller must ensure:
868
    /// - `ptr` points to valid data of size `len` with alignment `align`
869
    /// - `type_id` uniquely identifies the type
870
    /// - `custom_destructor` correctly drops the type at `ptr`
871
    /// - `len` and `align` match the actual type's layout
872
    /// - If `serialize_fn != 0`, it must be a valid function pointer of type `extern "C" fn(RefAny)
873
    ///   -> Json`
874
    /// - If `deserialize_fn != 0`, it must be a valid function pointer of type `extern "C" fn(Json)
875
    ///   -> ResultRefAnyString`
876
    ///
877
    /// # Zero-Sized Types
878
    ///
879
    /// Special case: ZSTs use a null pointer but still track the type info
880
    /// and call the destructor (which may have side effects even for ZSTs).
881
    ///
882
    /// # Panics
883
    ///
884
    /// Panics if `ptr` is null while `len > 0` (a non-empty value must have a
885
    /// valid backing pointer).
886
    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json
887
                                              // naming convention; internal access is required
888
305254
    pub fn new_c(
889
305254
        // *const T
890
305254
        ptr: *const c_void,
891
305254
        // sizeof(T)
892
305254
        len: usize,
893
305254
        // alignof(T)
894
305254
        align: usize,
895
305254
        // unique ID of the type (used for type comparison when downcasting)
896
305254
        type_id: u64,
897
305254
        // name of the class such as "app::MyData", usually compiler- or macro-generated
898
305254
        type_name: AzString,
899
305254
        custom_destructor: extern "C" fn(*mut c_void),
900
305254
        // function pointer for JSON serialization (0 = not set)
901
305254
        serialize_fn: usize,
902
305254
        // function pointer for JSON deserialization (0 = not set)
903
305254
        deserialize_fn: usize,
904
305254
    ) -> Self {
905
        use core::ptr;
906

            
907
        // CRITICAL: Validate input pointer for non-ZST types
908
        // A NULL pointer for a non-zero-sized type would cause UB when copying
909
305254
        assert!(
910
305254
            !(len > 0 && ptr.is_null()),
911
1
            "RefAny::new_c: NULL pointer passed for non-ZST type (size={}). This would cause \
912
1
             undefined behavior. Type: {:?}",
913
            len,
914
1
            type_name.as_str()
915
        );
916

            
917
        // Special case: Zero-sized types
918
        //
919
        // Calling `alloc(Layout { size: 0, .. })` is UB, so we use a null pointer.
920
        // The destructor is still called (it may have side effects even for ZSTs).
921
305253
        let (_internal_ptr, layout) = if len == 0 {
922
12613
            let _dummy: [u8; 0] = [];
923
12613
            (ptr::null_mut(), Layout::for_value(&_dummy))
924
        } else {
925
            // CRITICAL FIX: Use the caller-provided alignment, not alignment of [u8]
926
            //
927
            // Previous bug: `Layout::for_value(&[u8])` created align=1
928
            // This caused unaligned references when downcasting to types like i32 (align=4)
929
            //
930
            // Fixed: `Layout::from_size_align(len, align)` respects the type's alignment
931
292640
            let layout = Layout::from_size_align(len, align).expect("Failed to create layout");
932

            
933
            // Allocate heap memory with correct alignment
934
            // SAFETY: `layout` has non-zero size (this branch is `len != 0`), the
935
            // required precondition for `alloc`; null return is handled below.
936
292640
            let heap_struct_as_bytes = unsafe { alloc::alloc::alloc(layout) };
937

            
938
            // Handle allocation failure (aborts the program)
939
292640
            if heap_struct_as_bytes.is_null() {
940
2
                alloc::alloc::handle_alloc_error(layout);
941
292638
            }
942

            
943
            // Copy the data byte-by-byte to the heap
944
            // SAFETY: Both pointers are valid, non-overlapping, and properly aligned
945
292638
            unsafe { ptr::copy_nonoverlapping(ptr as *const u8, heap_struct_as_bytes, len) };
946

            
947
292638
            (heap_struct_as_bytes, layout)
948
        };
949

            
950
305251
        let ref_count_inner = RefCountInner {
951
305251
            _internal_ptr: _internal_ptr as *const c_void,
952
305251
            num_copies: AtomicUsize::new(1), // This is the first instance
953
305251
            num_refs: AtomicUsize::new(0),   // No borrows yet
954
305251
            num_mutable_refs: AtomicUsize::new(0), // No mutable borrows yet
955
305251
            _internal_len: len,
956
305251
            _internal_layout_size: layout.size(),
957
305251
            _internal_layout_align: layout.align(),
958
305251
            type_id,
959
305251
            type_name,
960
305251
            custom_destructor,
961
305251
            serialize_fn,
962
305251
            deserialize_fn,
963
305251
            update_fn: 0, // on-update observer not set by default; see set_update_fn
964
305251
        };
965

            
966
305251
        let sharing_info = RefCount::new(ref_count_inner);
967

            
968
305251
        Self {
969
305251
            sharing_info,
970
305251
            instance_id: 0, // Root instance
971
305251
        }
972
305251
    }
973

            
974
    /// Returns the raw data pointer for FFI downcasting.
975
    ///
976
    /// This is used by the `AZ_REFLECT` macros in C/C++ to access the
977
    /// type-erased data pointer for downcasting operations.
978
    ///
979
    /// # Safety
980
    ///
981
    /// The returned pointer must only be dereferenced after verifying
982
    /// the type ID matches the expected type. Callers are responsible
983
    /// for proper type safety checks.
984
    #[allow(clippy::used_underscore_binding)]
985
    // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is
986
    // required
987
    #[must_use]
988
186
    pub fn get_data_ptr(&self) -> *const c_void {
989
186
        self.sharing_info.downcast()._internal_ptr
990
186
    }
991

            
992
    /// Returns the byte length of the type-erased payload behind
993
    /// [`Self::get_data_ptr`] (`size_of::<T>()` of the stored type;
994
    /// `0` for ZSTs).
995
    #[allow(clippy::used_underscore_binding)]
996
    // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is
997
    // required
998
    #[must_use]
999
10
    pub fn get_data_len(&self) -> usize {
10
        self.sharing_info.downcast()._internal_len
10
    }
    /// Checks if this is the only `RefAny` instance with no active borrows.
    ///
    /// Returns `true` only if:
    /// - `num_copies == 1` (no clones exist)
    /// - `num_refs == 0` (no shared borrows active)
    /// - `num_mutable_refs == 0` (no mutable borrows active)
    ///
    /// Useful for checking if you have exclusive ownership.
    ///
    /// # Memory Ordering
    ///
    /// Uses `SeqCst` to ensure a consistent view across all three counters.
9
    pub(crate) fn has_no_copies(&self) -> bool {
9
        self.sharing_info
9
            .downcast()
9
            .num_copies
9
            .load(AtomicOrdering::SeqCst)
9
            == 1
5
            && self
5
                .sharing_info
5
                .downcast()
5
                .num_refs
5
                .load(AtomicOrdering::SeqCst)
5
                == 0
5
            && self
5
                .sharing_info
5
                .downcast()
5
                .num_mutable_refs
5
                .load(AtomicOrdering::SeqCst)
5
                == 0
9
    }
    /// Attempts to downcast to a shared reference of type `U`.
    ///
    /// Returns `None` if:
    /// - The stored type doesn't match `U` (type safety)
    /// - A mutable borrow is already active (borrow checking)
    /// - The pointer is null AND `U` is not zero-sized (uninitialized). A stored ZST has a null
    ///   pointer *by design* (nothing is allocated) and downcasts successfully, via a
    ///   dangling-but-aligned reference.
    ///
    /// # Type Safety
    ///
    /// Compares `type_id` at runtime before casting. This prevents casting
    /// `*const c_void` to the wrong type, which would be immediate UB.
    ///
    /// # Borrow Checking
    ///
    /// Checks `can_be_shared()` to enforce Rust's borrowing rules:
    /// - Multiple shared borrows are allowed
    /// - Shared and mutable borrows cannot coexist
    ///
    /// # Safety
    ///
    /// The `unsafe` cast is safe because:
    /// - Type ID check ensures `U` matches the stored type
    /// - Memory was allocated with correct alignment for `U`
    /// - Lifetime `'a` is tied to `&'a mut self`, preventing use-after-free
    /// - Reference count is incremented atomically before returning
    ///
    /// # Why `&mut self`?
    ///
    /// Requires `&mut self` to prevent multiple threads from calling this
    /// simultaneously on the same `RefAny`. The borrow checker enforces this.
    /// Clones of the `RefAny` can call this independently (they share data
    /// but have separate runtime borrow tracking).
    #[allow(clippy::used_underscore_binding)]
    // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is
    // required
    #[inline]
11569
    pub fn downcast_ref<U: 'static>(&mut self) -> Option<Ref<'_, U>> {
        // A RELEASED `RefAny` holds nothing to borrow. Checked explicitly
        // rather than relying on `get_type_id`'s `0` never colliding with a
        // real `TypeId` hash.
11569
        if self.sharing_info.is_released() {
2
            report_released_downcast();
2
            return None;
11567
        }
        // Runtime type check: prevent downcasting to wrong type
11567
        let stored_type_id = self.get_type_id();
11567
        let target_type_id = Self::get_type_id_static::<U>();
11567
        let is_same_type = stored_type_id == target_type_id;
11567
        if !is_same_type {
289
            return None;
11278
        }
        // AUDIT: ATOMIC shared-borrow acquisition.
        //
        // `RefAny` is `Sync` and clones share one `RefCountInner`, so the old
        // check-then-increment (`can_be_shared()` then `increase_ref()`) raced a
        // concurrent `downcast_mut` on another clone: both could pass their
        // pre-checks and hand out aliasing `&`/`&mut` to the same memory (UB).
        //
        // Fix (mirrors the `compare_exchange` discipline in `replace_contents`):
        // increment `num_refs` FIRST, then validate that no mutable borrow is
        // live. `SeqCst` imposes a single total order, so a writer (which CASes
        // `num_mutable_refs` 0->1 then reads `num_refs`) and this reader (which
        // adds to `num_refs` then reads `num_mutable_refs`) can never both
        // succeed — at least one observes the other's write. Back the increment
        // out on any failure path.
11278
        self.sharing_info.increase_ref();
11278
        if !self.sharing_info.can_be_shared() {
            // A mutable borrow is (being) acquired — release and fail.
9
            self.sharing_info.decrease_ref();
9
            return None;
11269
        }
        // Get data pointer from shared RefCountInner (stable while we hold the
        // shared borrow: `replace_contents` needs `num_refs == 0` to proceed).
11269
        let data_ptr = self.sharing_info.downcast()._internal_ptr;
        // A null `_internal_ptr` means either an uninitialized `RefAny` or a ZST:
        // `RefAny::new_c` stores ZSTs with a null pointer (they need no backing
        // allocation). A ZST is a *valid* stored value, so the type check above is
        // authoritative and a `&U` to a ZST dereferences no bytes — only a
        // *non-ZST* null pointer is a genuine failure.
11269
        if data_ptr.is_null() && size_of::<U>() != 0 {
            self.sharing_info.decrease_ref();
            return None;
11269
        }
        Some(Ref {
            // SAFETY: type check passed. For a real value `data_ptr` is non-null
            // and correctly aligned; for a ZST (null pointer) we hand out a
            // dangling-but-aligned `NonNull::dangling` reference, valid precisely
            // because it is never dereferenced for bytes.
            ptr: unsafe {
11269
                if data_ptr.is_null() {
5
                    &*core::ptr::NonNull::<U>::dangling().as_ptr()
                } else {
11264
                    &*(data_ptr as *const U)
                }
            },
11269
            sharing_info: self.sharing_info.clone(),
        })
11569
    }
    /// Attempts to downcast to a mutable reference of type `U`.
    ///
    /// Returns `None` if:
    /// - The stored type doesn't match `U` (type safety)
    /// - Any borrow is already active (borrow checking)
    /// - The pointer is null AND `U` is not zero-sized (uninitialized). A stored ZST has a null
    ///   pointer *by design* and downcasts successfully, via a dangling-but-aligned reference; note
    ///   that the on-update observer is NOT fired for a ZST (there are no bytes for it to
    ///   snapshot).
    ///
    /// # Type Safety
    ///
    /// Compares `type_id` at runtime before casting, preventing UB.
    ///
    /// # Borrow Checking
    ///
    /// Checks `can_be_shared_mut()` to enforce exclusive mutability:
    /// - No other borrows (shared or mutable) can be active
    /// - This is Rust's `&mut T` rule, enforced at runtime
    ///
    /// # Safety
    ///
    /// The `unsafe` cast is safe because:
    ///
    /// - Type ID check ensures `U` matches the stored type
    /// - Memory was allocated with correct alignment for `U`
    /// - Borrow check ensures no other references exist
    /// - Lifetime `'a` is tied to `&'a mut self`, preventing aliasing
    /// - Mutable reference count is incremented atomically
    ///
    /// # Memory Ordering
    ///
    /// The `increase_refmut()` uses `SeqCst`, ensuring other threads see
    /// this mutable borrow before they try to acquire any borrow.
    #[allow(clippy::used_underscore_binding)]
    // `_`-prefixed fields are an intentional FFI/api.json naming convention; internal access is
    // required
    #[inline]
4947
    pub fn downcast_mut<U: 'static>(&mut self) -> Option<RefMut<'_, U>> {
4947
        if self.sharing_info.is_released() {
1
            report_released_downcast();
1
            return None;
4946
        }
        // Runtime type check
4946
        let is_same_type = self.get_type_id() == Self::get_type_id_static::<U>();
4946
        if !is_same_type {
94
            return None;
4852
        }
        // AUDIT: ATOMIC exclusive-borrow acquisition (mirror `replace_contents`).
        //
        // The old check-then-increment (`can_be_shared_mut()` then
        // `increase_refmut()`) raced concurrent borrows on sibling clones and
        // could hand out an aliasing `&mut` (UB). Instead, `compare_exchange`
        // `num_mutable_refs` 0->1 to atomically take the exclusive slot, THEN
        // verify no shared borrow is live; release + fail otherwise. The CAS
        // both acquires and rejects a second mutable borrow in one step.
4852
        let inner = self.sharing_info.downcast();
4852
        if inner
4852
            .num_mutable_refs
4852
            .compare_exchange(0, 1, AtomicOrdering::SeqCst, AtomicOrdering::SeqCst)
4852
            .is_err()
        {
5
            return None;
4847
        }
4847
        if inner.num_refs.load(AtomicOrdering::SeqCst) != 0 {
            // A shared borrow is live — release the exclusive slot and fail.
8
            inner.num_mutable_refs.store(0, AtomicOrdering::SeqCst);
8
            return None;
4839
        }
        // Get data pointer from shared RefCountInner
4839
        let data_ptr = inner._internal_ptr;
        // A null `_internal_ptr` is either an uninitialized `RefAny` or a ZST
        // (stored with a null pointer; see `downcast_ref`). A non-ZST null is a
        // real failure — release the exclusive slot and bail. For a ZST there are
        // no bytes to observe or mutate, so skip the update observer below and
        // hand out a dangling-but-aligned `&mut`, keeping the exclusive borrow.
4839
        if data_ptr.is_null() {
2
            if size_of::<U>() != 0 {
                inner.num_mutable_refs.store(0, AtomicOrdering::SeqCst);
                return None;
2
            }
2
            return Some(RefMut {
2
                // SAFETY: type check passed; `U` is a ZST, so a dangling-but-
2
                // aligned pointer is a valid `&mut` never dereferenced for bytes.
2
                ptr: unsafe { &mut *core::ptr::NonNull::<U>::dangling().as_ptr() },
2
                sharing_info: self.sharing_info.clone(),
2
            });
4837
        }
        // Fire the on-update observer (if registered) BEFORE handing out the
        // mutable borrow: the callback sees the pre-mutation data + its byte
        // length, enabling undo/redo snapshots and client/server state sync.
4837
        let update_fn = inner.update_fn;
4837
        if update_fn != 0 {
            // SAFETY: `update_fn` is non-zero (checked) and, per `set_update_fn`'s
            // contract, is a valid `extern "C" fn(*const c_void, usize)`. The
            // round-trip goes through an int-to-pointer CAST (not a direct
            // usize->fn transmute): a transmuted integer carries no provenance,
            // which is UB to call (Miri rejects it); the cast re-acquires it.
1
            let cb: extern "C" fn(*const c_void, usize) =
1
                unsafe { core::mem::transmute(update_fn as *const ()) };
1
            let len = inner._internal_len;
            // AUDIT: the observer is a host-provided `extern "C"` fn. A Rust
            // panic escaping it would unwind across the FFI boundary (UB), so
            // contain it. `catch_unwind` needs `std`; `no_std` builds use
            // `panic = "abort"` where no unwinding can occur.
            #[cfg(feature = "std")]
            {
1
                drop(std::panic::catch_unwind(std::panic::AssertUnwindSafe(
1
                    || {
1
                        cb(data_ptr, len);
1
                    },
                )));
            }
            #[cfg(not(feature = "std"))]
            {
                cb(data_ptr, len);
            }
4836
        }
4837
        Some(RefMut {
4837
            // SAFETY: Type and borrow checks passed, exclusive access guaranteed
4837
            ptr: unsafe { &mut *(data_ptr as *mut U) },
4837
            sharing_info: self.sharing_info.clone(),
4837
        })
4947
    }
    /// Computes a runtime type ID from Rust's `TypeId`.
    ///
    /// Rust's `TypeId` is not `#[repr(C)]` and can't cross FFI boundaries.
    /// This function converts it to a `u64` by treating it as a byte array.
    ///
    /// # Safety
    ///
    /// Safe because:
    /// - `TypeId` is a valid type with a stable layout
    /// - We only read from it, never write
    /// - The slice lifetime is bounded by the function scope
    ///
    /// # Implementation
    ///
    /// Treats the `TypeId` as bytes and sums them with bit shifts to create
    /// a unique (but not cryptographically secure) hash.
    #[inline]
58684
    fn get_type_id_static<T: 'static>() -> u64 {
        use core::{any::TypeId, mem};
58684
        let t_id = TypeId::of::<T>();
        // SAFETY: TypeId is a valid type, we're only reading it
58684
        let struct_as_bytes = unsafe {
58684
            core::slice::from_raw_parts((&raw const t_id) as *const u8, size_of::<TypeId>())
        };
        // AUDIT: fold ALL bytes of the `TypeId` (16 on current toolchains),
        // not just the first 8. This u64 is the ONLY runtime type guard used by
        // `downcast_*`; dropping the high 8 bytes let two distinct types whose
        // `TypeId`s differ only in their upper half collide, permitting a
        // wrong-type downcast (UB). An FxHash-style rotate+multiply mixes every
        // byte into the result and is deterministic within a process run (which
        // is all `TypeId` itself guarantees).
938944
        struct_as_bytes.iter().fold(0u64, |hash, &b| {
938944
            (hash.rotate_left(5) ^ u64::from(b)).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95)
938944
        })
58684
    }
    /// Checks if the stored type matches the given type ID.
    #[must_use]
160
    pub fn is_type(&self, type_id: u64) -> bool {
160
        self.sharing_info.downcast().type_id == type_id
160
    }
    /// Returns the stored type ID.
    #[must_use]
188999
    pub fn get_type_id(&self) -> u64 {
        // A RELEASED `RefAny` has no type, and saying so beats aborting. This
        // is the gate every `downcast_ref` / `downcast_mut` passes through
        // first, so one check here makes the whole safe surface null-tolerant.
        // It used to reach `RefCount::downcast`'s assertion instead, which in a
        // `panic = "abort"` release build takes the process down — a
        // widget callback whose data had been released killed the app on an
        // ordinary focus change (device report, 2026-09-01). `0` is not a
        // `TypeId` any real `U` hashes to, so no downcast can match it.
188999
        if self.sharing_info.is_released() {
1
            return 0;
188998
        }
188998
        self.sharing_info.downcast().type_id
188999
    }
    /// Returns the human-readable type name for debugging.
    #[must_use]
33
    pub fn get_type_name(&self) -> AzString {
33
        if self.sharing_info.is_released() {
1
            return AzString::from_const_str("<released>");
32
        }
32
        self.sharing_info.downcast().type_name.clone()
33
    }
    /// Returns the current reference count (number of `RefAny` clones sharing this data).
    ///
    /// This is useful for debugging and metadata purposes.
    #[must_use]
154
    pub fn get_ref_count(&self) -> usize {
154
        self.sharing_info
154
            .downcast()
154
            .num_copies
154
            .load(AtomicOrdering::SeqCst)
154
    }
    /// Returns the serialize function pointer (0 = not set).
    ///
    /// This is used for JSON serialization of `RefAny` contents.
    #[must_use]
22
    pub fn get_serialize_fn(&self) -> usize {
22
        self.sharing_info.downcast().serialize_fn
22
    }
    /// Returns the deserialize function pointer (0 = not set).
    ///
    /// This is used for JSON deserialization to create a new `RefAny`.
    #[must_use]
20
    pub fn get_deserialize_fn(&self) -> usize {
20
        self.sharing_info.downcast().deserialize_fn
20
    }
    /// Sets the serialize function pointer.
    ///
    /// # Safety
    ///
    /// The caller must ensure the function pointer is valid and has the correct
    /// signature: `extern "C" fn(RefAny) -> Json`
    ///
    /// **Known issue:** `&mut self` is exclusive to this clone, not to the shared
    /// `RefCountInner`. Concurrent calls via different clones are a data race
    /// because `serialize_fn` is a plain `usize`, not atomic.
8
    pub fn set_serialize_fn(&mut self, serialize_fn: usize) {
        // FIXME: &mut self is exclusive to this clone only, not to the shared
        // RefCountInner — concurrent calls via different clones are a data race.
8
        let inner = self.sharing_info.ptr.cast_mut();
        // SAFETY: `inner` came from `Box::into_raw` and is live (we hold `self`).
8
        unsafe {
8
            (*inner).serialize_fn = serialize_fn;
8
        }
8
    }
    /// Sets the deserialize function pointer.
    ///
    /// # Safety
    ///
    /// The caller must ensure the function pointer is valid and has the correct
    /// signature: `extern "C" fn(Json) -> ResultRefAnyString`
    ///
    /// **Known issue:** `&mut self` is exclusive to this clone, not to the shared
    /// `RefCountInner`. Concurrent calls via different clones are a data race
    /// because `deserialize_fn` is a plain `usize`, not atomic.
8
    pub fn set_deserialize_fn(&mut self, deserialize_fn: usize) {
        // FIXME: &mut self is exclusive to this clone only, not to the shared
        // RefCountInner — concurrent calls via different clones are a data race.
8
        let inner = self.sharing_info.ptr.cast_mut();
        // SAFETY: `inner` came from `Box::into_raw` and is live (we hold `self`).
8
        unsafe {
8
            (*inner).deserialize_fn = deserialize_fn;
8
        }
8
    }
    /// Registers an on-update observer (`0` = unset). It is fired from
    /// [`Self::downcast_mut`] with the (data ptr, byte len) of the *pre-mutation*
    /// data, just before the mutable borrow is handed out — the foundation for
    /// undo/redo snapshots and client/server state sync.
    ///
    /// # Safety
    ///
    /// If `update_fn != 0` it must be a valid `extern "C" fn(*const c_void, usize)`.
    /// Same shared-`RefCountInner` caveat as [`Self::set_serialize_fn`]: `&mut self`
    /// is exclusive to this clone, not to the shared inner.
4
    pub fn set_update_fn(&mut self, update_fn: usize) {
4
        let inner = self.sharing_info.ptr.cast_mut();
        // SAFETY: `inner` came from `Box::into_raw` and is live (we hold `self`).
4
        unsafe {
4
            (*inner).update_fn = update_fn;
4
        }
4
    }
    /// Returns the registered on-update observer fn pointer (`0` = unset).
    #[must_use]
6
    pub fn get_update_fn(&self) -> usize {
6
        self.sharing_info.downcast().update_fn
6
    }
    /// Returns true if this `RefAny` supports JSON serialization.
    #[must_use]
14
    pub fn can_serialize(&self) -> bool {
14
        self.get_serialize_fn() != 0
14
    }
    /// Returns true if this `RefAny` type supports JSON deserialization.
    #[must_use]
12
    pub fn can_deserialize(&self) -> bool {
12
        self.get_deserialize_fn() != 0
12
    }
    /// Replaces the contents of this `RefAny` with a new value from another `RefAny`.
    ///
    /// This method:
    /// 1. Atomically acquires a mutable "lock" via `compare_exchange`
    /// 2. Calls the destructor on the old value
    /// 3. Deallocates the old memory
    /// 4. Copies the new value's memory
    /// 5. Updates metadata (`type_id`, `type_name`, destructor, serialize/deserialize fns)
    /// 6. Updates the shared _`internal_ptr` so ALL clones see the new data
    /// 7. Releases the lock
    ///
    /// Since all clones of a `RefAny` share the same `RefCountInner`, this change
    /// will be visible to ALL clones of this `RefAny`.
    ///
    /// # Returns
    ///
    /// - `true` if the replacement was successful
    /// - `false` if there are active borrows (would cause UB)
    ///
    /// # Thread Safety
    ///
    /// Uses `compare_exchange` to atomically acquire exclusive access, preventing
    /// any race condition between checking for borrows and modifying the data.
    ///
    /// # Safety
    ///
    /// Safe because:
    /// - We atomically acquire exclusive access before modifying
    /// - The old destructor is called before deallocation
    /// - Memory is properly allocated with correct alignment
    /// - All metadata is updated while holding the lock
    ///
    /// # Panics
    ///
    /// Panics if a memory `Layout` for the replacement value cannot be
    /// constructed (its size overflows `isize::MAX`).
    #[allow(clippy::used_underscore_binding)] // `_`-prefixed fields are an intentional FFI/api.json
                                              // naming convention; internal access is required
60
    pub fn replace_contents(&mut self, new_value: Self) -> bool {
        use core::ptr;
60
        let inner = self.sharing_info.ptr.cast_mut();
        // Atomically acquire exclusive access by setting num_mutable_refs to 1.
        // This uses compare_exchange to ensure no race condition:
        // - If num_mutable_refs is 0, set it to 1 (success)
        // - If num_mutable_refs is not 0, someone else has it (fail)
        // We also need to check num_refs == 0 atomically.
60
        let inner_ref = self.sharing_info.downcast();
        // First, try to acquire the mutable lock
60
        let mutable_lock_result = inner_ref.num_mutable_refs.compare_exchange(
            0, // expected: no mutable refs
            1, // desired: we take the mutable ref
60
            AtomicOrdering::SeqCst,
60
            AtomicOrdering::SeqCst,
        );
60
        if mutable_lock_result.is_err() {
            // Someone else has a mutable reference
1
            return false;
59
        }
        // Now check that there are no shared references
        // Note: We hold the mutable lock, so no new shared refs can be acquired
59
        if inner_ref.num_refs.load(AtomicOrdering::SeqCst) != 0 {
            // Release the lock and fail
1
            inner_ref.num_mutable_refs.store(0, AtomicOrdering::SeqCst);
1
            return false;
58
        }
        // We now have exclusive access - perform the replacement
        // SAFETY: we hold the exclusive lock (num_mutable_refs==1, num_refs==0),
        // so no live `Ref`/`RefMut` aliases the data; `inner` is the live
        // `RefCountInner` from `Box::into_raw`. Old data is destructed+freed with
        // its own stored layout before the pointer is overwritten, and the new
        // data is freshly allocated and byte-copied.
        unsafe {
            // Get old layout info before we overwrite it
58
            let old_ptr = (*inner)._internal_ptr;
58
            let old_len = (*inner)._internal_len;
58
            let old_layout_size = (*inner)._internal_layout_size;
58
            let old_layout_align = (*inner)._internal_layout_align;
58
            let old_destructor = (*inner).custom_destructor;
            // Step 1: Call destructor on old value (if non-ZST)
58
            if old_len > 0 && !old_ptr.is_null() {
57
                old_destructor(old_ptr.cast_mut());
57
            }
            // Step 2: Deallocate old memory (if non-ZST). Use the *checked*
            // `Layout::from_size_align` (not `_unchecked`): the stored
            // size/align came from a valid `Layout`, so it always succeeds, and
            // this shrinks the unchecked surface inside this unsafe block.
58
            if old_layout_size > 0 && !old_ptr.is_null() {
57
                let old_layout = Layout::from_size_align(old_layout_size, old_layout_align)
57
                    .expect("replace_contents: stored old layout was invalid");
57
                alloc::alloc::dealloc(old_ptr as *mut u8, old_layout);
57
            }
            // Get new value's metadata
58
            let new_inner = new_value.sharing_info.downcast();
58
            let new_ptr = new_inner._internal_ptr;
58
            let new_len = new_inner._internal_len;
58
            let new_layout_size = new_inner._internal_layout_size;
58
            let new_layout_align = new_inner._internal_layout_align;
            // Step 3: Allocate new memory and copy data
58
            let allocated_ptr = if new_len == 0 {
1
                ptr::null_mut()
            } else {
57
                let new_layout = Layout::from_size_align(new_len, new_layout_align)
57
                    .expect("Failed to create layout");
57
                let heap_ptr = alloc::alloc::alloc(new_layout);
57
                if heap_ptr.is_null() {
                    alloc::alloc::handle_alloc_error(new_layout);
57
                }
                // Copy data from new_value
57
                ptr::copy_nonoverlapping(new_ptr as *const u8, heap_ptr, new_len);
57
                heap_ptr
            };
            // Step 4: Update the shared internal pointer in RefCountInner
            // All clones will see this new pointer!
58
            (*inner)._internal_ptr = allocated_ptr as *const c_void;
            // Step 5: Update metadata in RefCountInner
58
            (*inner)._internal_len = new_len;
58
            (*inner)._internal_layout_size = new_layout_size;
58
            (*inner)._internal_layout_align = new_layout_align;
58
            (*inner).type_id = new_inner.type_id;
58
            (*inner).type_name = new_inner.type_name.clone();
58
            (*inner).custom_destructor = new_inner.custom_destructor;
58
            (*inner).serialize_fn = new_inner.serialize_fn;
58
            (*inner).deserialize_fn = new_inner.deserialize_fn;
58
            (*inner).update_fn = new_inner.update_fn;
        }
        // Release the mutable lock
58
        self.sharing_info
58
            .downcast()
58
            .num_mutable_refs
58
            .store(0, AtomicOrdering::SeqCst);
        // AUDIT: reclaim `new_value` instead of leaking it.
        //
        // The old code `mem::forget(new_value)` to stop `RefAny::drop` from
        // running the T-destructor a SECOND time on the bytes we just copied
        // into our own allocation — but that leaked `new_value`'s entire
        // `RefCountInner` box AND its heap data block on every single call.
        //
        // Instead, neutralize `new_value`'s destructor to a no-op and let the
        // normal refcount teardown run: it frees BOTH allocations (data block +
        // inner box) when this was the last reference, without re-running the
        // real T-destructor (which now lives on OUR inner, to run exactly once
        // when `self` is finally dropped). If `new_value` still had clones, the
        // no-op keeps them from double-dropping the shared T while their own
        // last drop still reclaims the shared block — no double free, no leak.
        #[allow(clippy::items_after_statements)]
58
        const extern "C" fn noop_destructor(_: *mut c_void) {}
58
        let new_inner = new_value.sharing_info.ptr.cast_mut();
58
        if !new_inner.is_null() {
            // SAFETY: `new_inner` came from `Box::into_raw` in `RefCount::new`
            // and is still alive (we hold `new_value`).
58
            unsafe {
58
                (*new_inner).custom_destructor = noop_destructor;
58
            }
        }
58
        drop(new_value);
58
        true
60
    }
}
impl Clone for RefAny {
    /// Creates a new `RefAny` sharing the same heap-allocated data.
    ///
    /// This is cheap (just increments a counter) and is how multiple parts
    /// of the code can hold references to the same data.
    ///
    /// # Reference Counting
    ///
    /// Atomically increments `num_copies` with `SeqCst` ordering before
    /// creating the clone. This ensures all threads see the updated count
    /// before the clone can be used.
    ///
    /// # Instance ID
    ///
    /// Each clone gets a unique `instance_id` based on the current copy count.
    /// The original has `instance_id=0`, the first clone gets `1`, etc.
    ///
    /// # Memory Ordering
    ///
    /// The `fetch_add` followed by `load` both use `SeqCst`:
    /// - `fetch_add`: Ensures the increment is visible to all threads
    /// - `load`: Gets the updated value for the `instance_id`
    ///
    /// This prevents race conditions where two threads clone simultaneously
    /// and both see the same `instance_id`.
    ///
    /// # Safety
    ///
    /// Safe because:
    ///
    /// - Atomic operations prevent data races
    /// - The heap allocation remains valid (only freed when count reaches 0)
    /// - `run_destructor` is set to `true` for all clones
873618
    fn clone(&self) -> Self {
        // Atomically increment the reference count
873618
        let inner = self.sharing_info.downcast();
873618
        let prev = inner.num_copies.fetch_add(1, AtomicOrdering::SeqCst);
873618
        let new_instance_id = (prev + 1) as u64;
873618
        Self {
873618
            // Data pointer is now in RefCountInner, shared automatically
873618
            sharing_info: RefCount {
873618
                ptr: self.sharing_info.ptr, // Share the same metadata (and data pointer)
873618
                run_destructor: true,       // This clone should decrement num_copies on drop
873618
            },
873618
            // Give this clone a unique ID based on the updated count
873618
            instance_id: new_instance_id,
873618
        }
873618
    }
}
impl Drop for RefAny {
    /// Empty drop implementation - all cleanup is handled by `RefCount::drop`.
    ///
    /// When a `RefAny` is dropped, its `sharing_info: RefCount` field is automatically
    /// dropped by Rust. The `RefCount::drop` implementation handles all cleanup:
    ///
    /// 1. Atomically decrements `num_copies` with `fetch_sub`
    /// 2. If the previous value was 1 (we're the last reference):
    ///    - Reclaims the `RefCountInner` via `Box::from_raw`
    ///    - Calls the custom destructor to run `T::drop()`
    ///    - Deallocates the heap memory with the stored layout
    ///
    /// # Why No Code Here?
    ///
    /// Previously, `RefAny::drop` handled cleanup, but this caused issues with the
    /// C API where `Ref<T>` and `RefMut<T>` guards (which clone the `RefCount`) need
    /// to keep the data alive even after the original `RefAny` is dropped.
    ///
    /// By moving all cleanup to `RefCount::drop`, we ensure that:
    /// - `RefAny::clone()` creates a `RefCount` with `run_destructor = true`
    /// - `AZ_REFLECT` macros create `Ref`/`RefMut` guards that clone `RefCount`
    /// - Each `RefCount` drop decrements the counter
    /// - Only the LAST drop (when `num_copies` was 1) cleans up memory
    ///
    /// See `RefCount::drop` for the full algorithm and safety documentation.
1178725
    fn drop(&mut self) {
        // RefCount::drop handles everything automatically.
        // The sharing_info field is dropped by Rust, triggering RefCount::drop.
1178725
    }
}
#[cfg(test)]
#[path = "refany_test.rs"]
mod refany_test;