1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(
5
    clippy::items_after_statements,
6
    clippy::redundant_clone,
7
    clippy::cast_possible_truncation,
8
    clippy::cast_sign_loss,
9
    trivial_casts,
10
    clippy::borrow_as_ptr,
11
    clippy::cast_ptr_alignment,
12
    clippy::unused_self,
13
    unused_qualifications,
14
    unreachable_pub,
15
    private_interfaces
16
)] // pedantic lints are noise in unsafe-exercising test code
17
mod audit_tests {
18
    use core::sync::atomic::{AtomicUsize, Ordering};
19

            
20
    use super::*;
21

            
22
    static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
23

            
24
    // The tests below share the single `DROP_COUNT` static: each resets it to 0
25
    // and then asserts an exact drop count. Under the default multi-threaded
26
    // test runner they would otherwise interleave and corrupt each other's
27
    // counts (a real, if test-only, isolation bug). Every `DROP_COUNT`-using
28
    // test takes this lock first to serialize; it is poison-tolerant so one
29
    // failing test does not cascade `.unwrap()` panics into the rest.
30
    static DROP_COUNT_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
31
5
    fn serialize_drop_count() -> std::sync::MutexGuard<'static, ()> {
32
5
        DROP_COUNT_SERIAL
33
5
            .lock()
34
5
            .unwrap_or_else(std::sync::PoisonError::into_inner)
35
5
    }
36

            
37
    struct DropCounter(#[allow(dead_code)] u32);
38
    impl Drop for DropCounter {
39
6
        fn drop(&mut self) {
40
6
            DROP_COUNT.fetch_add(1, Ordering::SeqCst);
41
6
        }
42
    }
43

            
44
    // AUDIT: exclusive borrow must be denied while a shared borrow is live and
45
    // vice-versa (runtime borrow checker), and must be recoverable after the
46
    // guard drops. Exercises the atomic acquire/release added to downcast_*.
47
    #[test]
48
1
    fn borrow_exclusion_and_recovery() {
49
        // The runtime borrow guard lives in the *shared* refcount inner, so it
50
        // is only observable across two clones (a single `RefAny` can't hold two
51
        // guards at once — the methods take `&mut self`). `b` shares `a`'s inner.
52
1
        let mut a = RefAny::new(7i32);
53
1
        let mut b = a.clone();
54

            
55
        {
56
1
            let r = a.downcast_ref::<i32>().unwrap();
57
1
            assert_eq!(*r, 7);
58
            // shared borrow live -> no mutable borrow via the shared inner
59
1
            assert!(b.downcast_mut::<i32>().is_none());
60
            // another shared borrow is fine
61
1
            assert!(b.downcast_ref::<i32>().is_some());
62
        }
63

            
64
        {
65
1
            let mut m = a.downcast_mut::<i32>().unwrap();
66
1
            *m = 42;
67
            // mutable borrow live -> no shared borrow via the shared inner
68
1
            assert!(b.downcast_ref::<i32>().is_none());
69
        }
70

            
71
1
        assert_eq!(*a.downcast_ref::<i32>().unwrap(), 42);
72
1
    }
73

            
74
    // AUDIT: wrong-type downcast must be rejected. Same type -> same id.
75
    #[test]
76
1
    fn type_id_guard() {
77
1
        let mut a = RefAny::new(1u64);
78
1
        assert!(a.downcast_ref::<i32>().is_none());
79
1
        assert!(a.downcast_ref::<u64>().is_some());
80

            
81
1
        assert_eq!(
82
1
            RefAny::get_type_id_static::<u64>(),
83
1
            RefAny::get_type_id_static::<u64>()
84
        );
85
1
        assert_ne!(
86
1
            RefAny::get_type_id_static::<u64>(),
87
1
            RefAny::get_type_id_static::<i64>()
88
        );
89
1
    }
90

            
91
    // AUDIT: replace_contents must run each stored value's destructor exactly
92
    // once (old value on replace, new value on final drop) and must not leak.
93
    #[test]
94
1
    fn replace_contents_drops_exactly_once() {
95
1
        let _serial = serialize_drop_count();
96
1
        DROP_COUNT.store(0, Ordering::SeqCst);
97
        {
98
1
            let mut a = RefAny::new(DropCounter(1));
99
1
            let b = RefAny::new(DropCounter(2));
100
1
            assert!(a.replace_contents(b));
101
            // The original `a` value was dropped during replacement.
102
1
            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
103
            // `a` now holds the (copied) `b` value; dropped at end of scope.
104
        }
105
        // Two DropCounter values were constructed; both must be dropped once.
106
1
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 2);
107
1
    }
108

            
109
    // AUDIT: replace_contents must fail (return false) while a borrow is live.
110
    #[test]
111
1
    fn replace_contents_denied_while_borrowed() {
112
1
        let mut a = RefAny::new(1i32);
113
        // Clone first: `r` will exclusively borrow `a`, so the sibling clone
114
        // must exist beforehand. Both share the same inner RefCountInner.
115
1
        let mut a2 = a.clone();
116
1
        let r = a.downcast_ref::<i32>().unwrap();
117
        // A live shared borrow (num_refs != 0) on the shared inner must block
118
        // replace_contents via the sibling clone.
119
1
        assert!(!a2.replace_contents(RefAny::new(2i32)));
120
1
        drop(r);
121
1
        assert!(a2.replace_contents(RefAny::new(2i32)));
122
1
    }
123

            
124
    // ---- Miri-focused unit tests -------------------------------------------
125
    // These exercise the pure-Rust memory behavior of each unsafe path so Miri
126
    // can detect UB (bad provenance, misalignment, use-after-free, leaks,
127
    // refcount corruption). No FFI, no threads, no OS calls; tiny allocations.
128

            
129
    // MIRI: covers RefAny::new + new_c alloc/copy_nonoverlapping + downcast_ref
130
    // (&*(ptr as *const U)) + the final Drop path (Box::from_raw + dealloc +
131
    // custom destructor). A non-Copy heap type checks the destructor runs.
132
    #[test]
133
1
    fn miri_new_downcast_drop_roundtrip() {
134
1
        let _serial = serialize_drop_count();
135
1
        DROP_COUNT.store(0, Ordering::SeqCst);
136
        {
137
1
            let mut a = RefAny::new(DropCounter(9));
138
            // downcast_ref exercises the type-id guard + aligned pointer cast.
139
1
            assert!(a.downcast_ref::<DropCounter>().is_some());
140
1
            assert!(a.downcast_ref::<u8>().is_none());
141
        }
142
1
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
143
1
    }
144

            
145
    // MIRI: alignment correctness of new_c's Layout::from_size_align path. An
146
    // over-aligned payload downcast to a misaligned pointer would be UB.
147
    #[test]
148
1
    fn miri_alignment_preserved() {
149
        #[repr(align(16))]
150
        #[derive(Debug)]
151
        struct Over(u64);
152
1
        let mut a = RefAny::new(Over(0xABCD));
153
1
        let r = a.downcast_ref::<Over>().unwrap();
154
1
        assert_eq!(r.0, 0xABCD);
155
1
        assert_eq!((&raw const *r) as usize % 16, 0);
156
1
    }
157

            
158
    // MIRI: clone shares one RefCountInner; num_copies increments on clone and
159
    // decrements on drop (RefCount::clone / RefCount::drop fetch paths). Data
160
    // must survive while any clone lives and be freed exactly once at the end.
161
    #[test]
162
1
    fn miri_clone_refcount_increment_decrement() {
163
1
        let _serial = serialize_drop_count();
164
1
        DROP_COUNT.store(0, Ordering::SeqCst);
165
        {
166
1
            let a = RefAny::new(DropCounter(1));
167
1
            assert_eq!(a.get_ref_count(), 1);
168
1
            let b = a.clone();
169
1
            assert_eq!(a.get_ref_count(), 2);
170
1
            assert_eq!(b.get_ref_count(), 2);
171
            {
172
1
                let c = b.clone();
173
1
                assert_eq!(c.get_ref_count(), 3);
174
            }
175
            // c dropped -> back to 2, nothing freed yet.
176
1
            assert_eq!(a.get_ref_count(), 2);
177
1
            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0);
178
        }
179
        // all clones dropped -> data destructed exactly once.
180
1
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
181
1
    }
182

            
183
    // MIRI: downcast_mut hands out &mut *(ptr as *mut U); mutation must be
184
    // visible through a shared clone (shared RefCountInner data pointer).
185
    #[test]
186
1
    fn miri_downcast_mut_mutation_visible_across_clones() {
187
1
        let mut a = RefAny::new(10u32);
188
1
        let mut b = a.clone();
189
1
        {
190
1
            let mut m = a.downcast_mut::<u32>().unwrap();
191
1
            *m += 5;
192
1
        }
193
1
        assert_eq!(*b.downcast_ref::<u32>().unwrap(), 15);
194
1
    }
195

            
196
    // MIRI: the runtime borrow refcount on the shared inner. Exercises
197
    // increase_ref/decrease_ref/increase_refmut/decrease_refmut and the
198
    // can_be_shared / can_be_shared_mut predicates directly, plus the
199
    // checked_sub underflow guard (decrement at zero must saturate, not wrap).
200
    #[test]
201
1
    fn miri_borrow_counter_transitions_and_underflow_guard() {
202
1
        let a = RefAny::new(0i32);
203
1
        let rc = &a.sharing_info;
204

            
205
1
        assert!(rc.can_be_shared());
206
1
        assert!(rc.can_be_shared_mut());
207

            
208
1
        rc.increase_ref();
209
1
        assert!(rc.can_be_shared()); // shared borrows coexist
210
1
        assert!(!rc.can_be_shared_mut()); // but block a mutable borrow
211
1
        rc.decrease_ref();
212
1
        assert!(rc.can_be_shared_mut());
213

            
214
1
        rc.increase_refmut();
215
1
        assert!(!rc.can_be_shared()); // mutable borrow blocks shared
216
1
        assert!(!rc.can_be_shared_mut());
217
1
        rc.decrease_refmut();
218
1
        assert!(rc.can_be_shared_mut());
219

            
220
        // Underflow guard: extra decrements must saturate at 0, never wrap to
221
        // usize::MAX (which would permanently break the borrow checker).
222
1
        rc.decrease_ref();
223
1
        rc.decrease_refmut();
224
1
        assert!(rc.can_be_shared());
225
1
        assert!(rc.can_be_shared_mut());
226
1
    }
227

            
228
    // MIRI: get_type_id_static reads TypeId via from_raw_parts and folds ALL
229
    // bytes. Same type -> same id (stable within a run); distinct types differ.
230
    #[test]
231
1
    fn miri_type_id_static_stable_and_distinct() {
232
1
        assert_eq!(
233
1
            RefAny::get_type_id_static::<(u8, u64)>(),
234
1
            RefAny::get_type_id_static::<(u8, u64)>()
235
        );
236
1
        assert_ne!(
237
1
            RefAny::get_type_id_static::<u32>(),
238
1
            RefAny::get_type_id_static::<[u32; 2]>()
239
        );
240
1
    }
241

            
242
    // MIRI: ZST payload uses a null data pointer but must still construct, clone,
243
    // run its destructor exactly once, and downcast (a ZST reference reads no
244
    // bytes, so a dangling-but-aligned pointer is a valid reference).
245
    #[test]
246
1
    fn miri_zst_roundtrip_and_destructor() {
247
1
        let _serial = serialize_drop_count();
248
1
        DROP_COUNT.store(0, Ordering::SeqCst);
249
        struct ZstDrop;
250
        impl Drop for ZstDrop {
251
1
            fn drop(&mut self) {
252
1
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
253
1
            }
254
        }
255
        {
256
1
            let mut a = RefAny::new(ZstDrop);
257
1
            assert_eq!(a.get_data_len(), 0);
258
            // downcast_ref succeeds for a ZST (dangling ref, no bytes read); the
259
            // returned guard drops here without running the value's destructor.
260
1
            assert!(a.downcast_ref::<ZstDrop>().is_some());
261
1
            let _b = a.clone();
262
        }
263
1
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
264
1
    }
265

            
266
    // MIRI: replace_contents alloc/dealloc/copy path plus the neutralized
267
    // new_value destructor. Old value destructed once, new value destructed
268
    // once at final drop, with no leak/double-free of either heap block.
269
    #[test]
270
1
    fn miri_replace_contents_alloc_paths() {
271
1
        let _serial = serialize_drop_count();
272
1
        DROP_COUNT.store(0, Ordering::SeqCst);
273
        {
274
1
            let mut a = RefAny::new(DropCounter(1));
275
1
            assert!(a.replace_contents(RefAny::new(DropCounter(2))));
276
1
            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1); // old value gone
277
1
            assert_eq!(a.downcast_ref::<DropCounter>().unwrap().0, 2u32);
278
        }
279
1
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 2);
280
1
    }
281

            
282
    // MIRI: replacing across differing sizes/alignments (u8 -> u64) reallocates
283
    // correctly and keeps the shared pointer aligned for the new type.
284
    #[test]
285
1
    fn miri_replace_contents_changes_layout() {
286
1
        let mut a = RefAny::new(7u8);
287
1
        assert!(a.replace_contents(RefAny::new(0x1122_3344_5566_7788u64)));
288
        {
289
            // downcast_ref takes &mut self, so scope the guard before the next call.
290
1
            let r = a.downcast_ref::<u64>().unwrap();
291
1
            assert_eq!(*r, 0x1122_3344_5566_7788u64);
292
1
            assert_eq!((&raw const *r) as usize % core::mem::align_of::<u64>(), 0);
293
        }
294
        // old u8 type must no longer downcast.
295
1
        assert!(a.downcast_ref::<u8>().is_none());
296
1
    }
297

            
298
    // MIRI: RefCount clone/drop in isolation keeps the inner alive until the
299
    // last handle drops (Box::into_raw / Box::from_raw balance).
300
    #[test]
301
1
    fn miri_refcount_clone_keeps_inner_alive() {
302
1
        let a = RefAny::new(5usize);
303
1
        let rc0 = a.sharing_info.clone(); // +1 copy
304
1
        let rc1 = rc0.clone(); // +1 copy
305
1
        assert_eq!(a.get_ref_count(), 3);
306
1
        drop(rc1);
307
1
        drop(rc0);
308
1
        assert_eq!(a.get_ref_count(), 1);
309
        // `a` still usable -> inner not freed.
310
1
        assert_eq!(*a.clone().downcast_ref::<usize>().unwrap(), 5);
311
1
    }
312
}
313

            
314
#[cfg(test)]
315
#[allow(
316
    clippy::items_after_statements,
317
    clippy::redundant_clone,
318
    clippy::needless_pass_by_value,
319
    clippy::needless_range_loop,
320
    clippy::cast_possible_truncation,
321
    clippy::cast_sign_loss,
322
    clippy::cast_lossless,
323
    clippy::float_cmp,
324
    clippy::unreadable_literal,
325
    clippy::unusual_byte_groupings,
326
    clippy::many_single_char_names,
327
    clippy::used_underscore_binding,
328
    clippy::borrow_as_ptr,
329
    clippy::cast_ptr_alignment,
330
    clippy::fn_to_numeric_cast_any,
331
    trivial_casts,
332
    unused_qualifications,
333
    unreachable_pub,
334
    private_interfaces,
335
    missing_debug_implementations,
336
    missing_copy_implementations
337
)] // pedantic lints are noise in unsafe-exercising test code
338
mod autotest_generated {
339
    use alloc::{string::String, vec::Vec};
340
    use core::{
341
        ffi::c_void,
342
        sync::atomic::{AtomicUsize, Ordering},
343
    };
344

            
345
    use super::*;
346

            
347
    /// Destructor for payloads that need no drop glue (`Copy` types built via
348
    /// the raw C-ABI `new_c` path).
349
    extern "C" fn noop_destructor(_: *mut c_void) {}
350

            
351
    /// Store `value` in a `RefAny` and read it back out: the byte-copy into the
352
    /// heap allocation and the type-checked pointer cast must be lossless.
353
    fn round_trip<T: 'static + Clone + PartialEq + core::fmt::Debug>(value: T) {
354
        let mut a = RefAny::new(value.clone());
355
        let r = a
356
            .downcast_ref::<T>()
357
            .expect("downcast to the stored type must succeed");
358
        assert_eq!(*r, value);
359
    }
360

            
361
    // ---- RefAny::new_c — raw C-ABI constructor, malformed/boundary inputs ----
362

            
363
    // A NULL pointer with a non-zero length is the classic FFI mistake: copying
364
    // from it would be UB, so `new_c` must panic instead of reading it.
365
    #[test]
366
    #[should_panic(expected = "NULL pointer passed for non-ZST type")]
367
    fn new_c_null_ptr_with_nonzero_len_panics() {
368
        drop(RefAny::new_c(
369
            core::ptr::null(),
370
            4,
371
            4,
372
            RefAny::get_type_id_static::<u32>(),
373
            AzString::from_const_str("autotest::NullPtr"),
374
            noop_destructor,
375
            0,
376
            0,
377
        ));
378
    }
379

            
380
    // A non-power-of-two alignment cannot form a valid `Layout`; it must panic
381
    // before allocating rather than allocate with a bogus layout (which would
382
    // make the matching `dealloc` in `drop` UB).
383
    #[test]
384
    #[should_panic(expected = "Failed to create layout")]
385
    fn new_c_non_power_of_two_align_panics() {
386
        let value: u32 = 7;
387
        drop(RefAny::new_c(
388
            (&raw const value).cast::<c_void>(),
389
            4,
390
            3, // not a power of two
391
            RefAny::get_type_id_static::<u32>(),
392
            AzString::from_const_str("autotest::BadAlign"),
393
            noop_destructor,
394
            0,
395
            0,
396
        ));
397
    }
398

            
399
    // `usize::MAX` bytes overflows `isize::MAX` and cannot be a `Layout`: the
400
    // checked constructor must reject it (no silent overflow into a tiny alloc).
401
    #[test]
402
    #[should_panic(expected = "Failed to create layout")]
403
    fn new_c_huge_len_panics_instead_of_overflowing() {
404
        let value: u8 = 1;
405
        drop(RefAny::new_c(
406
            (&raw const value).cast::<c_void>(),
407
            usize::MAX,
408
            1,
409
            RefAny::get_type_id_static::<u8>(),
410
            AzString::from_const_str("autotest::HugeLen"),
411
            noop_destructor,
412
            0,
413
            0,
414
        ));
415
    }
416

            
417
    // len == 0 is the ZST path: NULL data pointer is legal, `align` is ignored
418
    // (even a nonsensical 0), nothing is allocated, and a ZST still downcasts
419
    // (via a dangling-but-aligned reference — there are no bytes to read).
420
    #[test]
421
    fn new_c_zero_len_null_ptr_is_a_clean_zst() {
422
        let mut a = RefAny::new_c(
423
            core::ptr::null(),
424
            0,
425
            0, // invalid alignment, but unused on the ZST path
426
            RefAny::get_type_id_static::<()>(),
427
            AzString::from_const_str("autotest::Zst"),
428
            noop_destructor,
429
            0,
430
            0,
431
        );
432
        assert_eq!(a.get_data_len(), 0);
433
        assert!(a.get_data_ptr().is_null());
434
        assert!(a.is_type(RefAny::get_type_id_static::<()>()));
435
        // Type matches and a `&()`/`&mut ()` needs no backing bytes, so the
436
        // downcast succeeds; each temporary guard releases its borrow slot when it
437
        // drops at the end of its statement.
438
        assert!(a.downcast_ref::<()>().is_some());
439
        assert!(a.downcast_mut::<()>().is_some());
440
        assert!(a.sharing_info.can_be_shared_mut());
441
    }
442

            
443
    // Round-trip through the raw C-ABI constructor: what `new_c` encodes,
444
    // `downcast_ref` must decode bit-for-bit.
445
    #[test]
446
    fn new_c_round_trip_matches_rust_constructor() {
447
        let value: u64 = 0xDEAD_BEEF_CAFE_BABE;
448
        let mut a = RefAny::new_c(
449
            (&raw const value).cast::<c_void>(),
450
            core::mem::size_of::<u64>(),
451
            core::mem::align_of::<u64>(),
452
            RefAny::get_type_id_static::<u64>(),
453
            AzString::from_const_str("u64"),
454
            noop_destructor,
455
            7,
456
            9,
457
        );
458
        assert_eq!(a.get_data_len(), core::mem::size_of::<u64>());
459
        assert_eq!(a.get_ref_count(), 1);
460
        assert_eq!(a.get_serialize_fn(), 7);
461
        assert_eq!(a.get_deserialize_fn(), 9);
462
        assert!(a.can_serialize());
463
        assert!(a.can_deserialize());
464
        assert_eq!(*a.downcast_ref::<u64>().unwrap(), value);
465
    }
466

            
467
    // The runtime guard is the type ID, nothing else: a matching size, name and
468
    // destructor must NOT be enough to downcast if the ID differs by one bit.
469
    #[test]
470
    fn new_c_wrong_type_id_rejects_downcast() {
471
        let value: u64 = 0x0102_0304_0506_0708;
472
        let real_id = RefAny::get_type_id_static::<u64>();
473
        let mut a = RefAny::new_c(
474
            (&raw const value).cast::<c_void>(),
475
            core::mem::size_of::<u64>(),
476
            core::mem::align_of::<u64>(),
477
            real_id ^ 1, // one bit off
478
            AzString::from_const_str("u64"),
479
            noop_destructor,
480
            0,
481
            0,
482
        );
483
        assert!(!a.is_type(real_id));
484
        assert!(a.downcast_ref::<u64>().is_none());
485
        assert!(a.downcast_mut::<u64>().is_none());
486
        // The rejected downcasts must not have left a borrow behind.
487
        assert!(a.sharing_info.can_be_shared_mut());
488
    }
489

            
490
    // Over-alignment (align > len) is a valid `Layout`; the payload must land on
491
    // an address that satisfies the requested alignment.
492
    #[test]
493
    fn new_c_over_aligned_small_payload() {
494
        let value: u8 = 0x5A;
495
        let mut a = RefAny::new_c(
496
            (&raw const value).cast::<c_void>(),
497
            1,
498
            16,
499
            RefAny::get_type_id_static::<u8>(),
500
            AzString::from_const_str("u8"),
501
            noop_destructor,
502
            0,
503
            0,
504
        );
505
        assert_eq!(a.get_data_ptr() as usize % 16, 0);
506
        assert_eq!(*a.downcast_ref::<u8>().unwrap(), 0x5A);
507
    }
508

            
509
    // The type name is arbitrary caller-supplied UTF-8 (generated by foreign
510
    // codegen): empty, unicode, RTL overrides and embedded NULs must survive.
511
    #[test]
512
    fn new_c_preserves_unicode_and_empty_type_names() {
513
        let value: u32 = 0;
514
        let weird = "app::💥Ünïcødé<T>\u{202E}rtl\u{0}nul";
515
        let a = RefAny::new_c(
516
            (&raw const value).cast::<c_void>(),
517
            4,
518
            4,
519
            1,
520
            AzString::from(String::from(weird)),
521
            noop_destructor,
522
            0,
523
            0,
524
        );
525
        assert_eq!(a.get_type_name().as_str(), weird);
526

            
527
        let b = RefAny::new_c(
528
            (&raw const value).cast::<c_void>(),
529
            4,
530
            4,
531
            2,
532
            AzString::from_const_str(""),
533
            noop_destructor,
534
            0,
535
            0,
536
        );
537
        assert_eq!(b.get_type_name().as_str(), "");
538
    }
539

            
540
    // ---- RefAny::new — post-construction invariants ----
541

            
542
    #[test]
543
    fn new_invariants_hold() {
544
        let mut a = RefAny::new(0x1122_3344u32);
545
        assert_eq!(a.get_data_len(), core::mem::size_of::<u32>());
546
        assert!(!a.get_data_ptr().is_null());
547
        assert_eq!(a.get_data_ptr() as usize % core::mem::align_of::<u32>(), 0);
548
        assert_eq!(a.get_type_id(), RefAny::get_type_id_static::<u32>());
549
        assert!(a.is_type(RefAny::get_type_id_static::<u32>()));
550
        assert_eq!(a.get_type_name().as_str(), "u32");
551
        assert_eq!(a.get_ref_count(), 1);
552
        assert!(a.has_no_copies());
553
        assert_eq!(a.get_serialize_fn(), 0);
554
        assert_eq!(a.get_deserialize_fn(), 0);
555
        assert_eq!(a.get_update_fn(), 0);
556
        assert!(!a.can_serialize());
557
        assert!(!a.can_deserialize());
558
        assert!(a.sharing_info.can_be_shared());
559
        assert!(a.sharing_info.can_be_shared_mut());
560
        assert_eq!(a.instance_id, 0);
561
        assert_eq!(*a.downcast_ref::<u32>().unwrap(), 0x1122_3344);
562
    }
563

            
564
    // A zero-length array of an 8-aligned element is still a ZST: `new` must take
565
    // the null-pointer path (no zero-size allocation, which would be UB).
566
    #[test]
567
    fn new_zero_sized_array_of_aligned_type_is_a_zst() {
568
        let mut a = RefAny::new([0u64; 0]);
569
        assert_eq!(a.get_data_len(), 0);
570
        assert!(a.get_data_ptr().is_null());
571
        assert_eq!(
572
            a.sharing_info
573
                .debug_get_refcount_copied()
574
                ._internal_layout_size,
575
            0
576
        );
577
        assert!(a.downcast_ref::<[u64; 0]>().is_some());
578
        assert_eq!(a.get_ref_count(), 1);
579
    }
580

            
581
    // Large + heavily over-aligned payload: the alignment recorded at
582
    // construction must be honoured by the allocation, or every downcast would
583
    // hand out a misaligned reference.
584
    #[test]
585
    fn new_large_over_aligned_payload_round_trips() {
586
        #[repr(align(64))]
587
        #[derive(Clone)]
588
        struct Big([u8; 4096]);
589

            
590
        let mut a = RefAny::new(Big([0xAB; 4096]));
591
        assert_eq!(a.get_data_len(), 4096);
592
        assert_eq!(a.get_data_ptr() as usize % 64, 0);
593
        let r = a.downcast_ref::<Big>().unwrap();
594
        assert_eq!((&raw const *r) as usize % 64, 0);
595
        assert!(r.0.iter().all(|&b| b == 0xAB));
596
    }
597

            
598
    // ---- numeric limits / round-trip ----
599

            
600
    #[test]
601
    fn integer_limits_round_trip() {
602
        round_trip(u8::MIN);
603
        round_trip(u8::MAX);
604
        round_trip(i8::MIN);
605
        round_trip(i8::MAX);
606
        round_trip(u16::MAX);
607
        round_trip(i16::MIN);
608
        round_trip(u32::MAX);
609
        round_trip(i32::MIN);
610
        round_trip(u64::MAX);
611
        round_trip(i64::MIN);
612
        // u128/i128 are 16-aligned on most targets -> exercises the align path
613
        round_trip(u128::MAX);
614
        round_trip(i128::MIN);
615
        round_trip(i128::MAX);
616
        round_trip(usize::MAX);
617
        round_trip(isize::MIN);
618
        round_trip(0usize);
619
    }
620

            
621
    // Floats are copied as raw bytes, so every bit pattern (NaN payloads, signed
622
    // zero, infinities) must survive unchanged — no normalization, no rounding.
623
    #[test]
624
    fn float_extremes_round_trip_bit_exact() {
625
        let mut nan = RefAny::new(f64::NAN);
626
        assert!(nan.downcast_ref::<f64>().unwrap().is_nan());
627

            
628
        // A NaN with a non-canonical payload must come back bit-identical.
629
        let bits = 0x7FF0_0000_0000_0001u64;
630
        let mut payload_nan = RefAny::new(f64::from_bits(bits));
631
        assert_eq!(payload_nan.downcast_ref::<f64>().unwrap().to_bits(), bits);
632

            
633
        let mut neg_zero = RefAny::new(-0.0f64);
634
        let nz = neg_zero.downcast_ref::<f64>().unwrap();
635
        assert!(*nz == 0.0 && nz.is_sign_negative());
636
        drop(nz);
637

            
638
        let mut inf = RefAny::new(f32::NEG_INFINITY);
639
        assert_eq!(*inf.downcast_ref::<f32>().unwrap(), f32::NEG_INFINITY);
640
        // f32 and f64 are distinct types even though both are "floats".
641
        assert!(inf.downcast_ref::<f64>().is_none());
642

            
643
        round_trip(f64::MIN);
644
        round_trip(f64::MAX);
645
        round_trip(f64::MIN_POSITIVE);
646
        round_trip(f32::EPSILON);
647
        round_trip(f32::MAX);
648
    }
649

            
650
    // Owned heap payloads: the value is moved in (`mem::forget` on the original)
651
    // and dropped exactly once at the end — a double-drop here would be a
652
    // double-free of the String/Vec buffers.
653
    #[test]
654
    fn owned_unicode_payloads_round_trip() {
655
        round_trip(String::new());
656
        round_trip(String::from("héllo 🌍 \u{202E}rtl\u{0}nul"));
657
        round_trip('🌍');
658

            
659
        let v: Vec<String> = vec![String::from("a"), String::from("🎉"), String::new()];
660
        round_trip(v);
661
    }
662

            
663
    // A struct with interior padding is byte-copied, padding included: the copy
664
    // must not disturb the initialized fields.
665
    #[test]
666
    fn padded_struct_round_trips() {
667
        #[derive(Clone, PartialEq, Debug)]
668
        #[repr(C)]
669
        struct Padded {
670
            a: u8,
671
            b: u64,
672
            c: u8,
673
        }
674
        round_trip(Padded {
675
            a: 0xFF,
676
            b: u64::MAX,
677
            c: 0x01,
678
        });
679
    }
680

            
681
    // ---- setters: 0 / 1 / usize::MAX (never dereferenced by azul-core) ----
682

            
683
    #[test]
684
    fn set_serialize_fn_zero_and_extremes() {
685
        let mut a = RefAny::new(1u32);
686
        assert_eq!(a.get_serialize_fn(), 0);
687
        assert!(!a.can_serialize());
688

            
689
        a.set_serialize_fn(usize::MAX);
690
        assert_eq!(a.get_serialize_fn(), usize::MAX);
691
        assert!(a.can_serialize());
692

            
693
        a.set_serialize_fn(1);
694
        assert_eq!(a.get_serialize_fn(), 1);
695
        assert!(a.can_serialize());
696

            
697
        a.set_serialize_fn(0);
698
        assert_eq!(a.get_serialize_fn(), 0);
699
        assert!(!a.can_serialize());
700

            
701
        // The fn pointer lives in the SHARED inner, so a clone's setter is
702
        // visible through the original.
703
        let mut b = a.clone();
704
        b.set_serialize_fn(42);
705
        assert_eq!(a.get_serialize_fn(), 42);
706
        assert!(a.can_serialize());
707
        b.set_serialize_fn(0);
708
        assert!(!a.can_serialize());
709
    }
710

            
711
    #[test]
712
    fn set_deserialize_fn_zero_and_extremes() {
713
        let mut a = RefAny::new(1u32);
714
        assert_eq!(a.get_deserialize_fn(), 0);
715
        assert!(!a.can_deserialize());
716

            
717
        a.set_deserialize_fn(usize::MAX);
718
        assert_eq!(a.get_deserialize_fn(), usize::MAX);
719
        assert!(a.can_deserialize());
720

            
721
        a.set_deserialize_fn(1);
722
        assert_eq!(a.get_deserialize_fn(), 1);
723

            
724
        a.set_deserialize_fn(0);
725
        assert_eq!(a.get_deserialize_fn(), 0);
726
        assert!(!a.can_deserialize());
727

            
728
        let mut b = a.clone();
729
        b.set_deserialize_fn(42);
730
        assert_eq!(a.get_deserialize_fn(), 42);
731
        b.set_deserialize_fn(0);
732
        assert!(!a.can_deserialize());
733
    }
734

            
735
    // `set_update_fn` only *stores* the address; a bogus value must round-trip
736
    // and must be resettable to 0. (Deliberately no `downcast_mut` while the
737
    // observer is bogus — `downcast_mut` transmutes and CALLS it.)
738
    #[test]
739
    fn set_update_fn_zero_and_extremes() {
740
        let mut a = RefAny::new(1u32);
741
        assert_eq!(a.get_update_fn(), 0);
742

            
743
        a.set_update_fn(usize::MAX);
744
        assert_eq!(a.get_update_fn(), usize::MAX);
745

            
746
        a.set_update_fn(0);
747
        assert_eq!(a.get_update_fn(), 0);
748
        // With the observer unset again, mutable borrows work as normal.
749
        assert!(a.downcast_mut::<u32>().is_some());
750
    }
751

            
752
    // The registered observer must fire exactly once per *successful*
753
    // `downcast_mut`, and must see the PRE-mutation bytes + the payload length.
754
    static UPDATE_CALLS: AtomicUsize = AtomicUsize::new(0);
755
    static UPDATE_LEN: AtomicUsize = AtomicUsize::new(0);
756
    static UPDATE_PRE_VALUE: AtomicUsize = AtomicUsize::new(0);
757

            
758
    extern "C" fn record_update(ptr: *const c_void, len: usize) {
759
        UPDATE_CALLS.fetch_add(1, Ordering::SeqCst);
760
        UPDATE_LEN.store(len, Ordering::SeqCst);
761
        if !ptr.is_null() && len == core::mem::size_of::<u32>() {
762
            // SAFETY: only installed on a `RefAny` holding a `u32`, and
763
            // `downcast_mut` fires it with that live payload pointer.
764
            let pre = unsafe { core::ptr::read_unaligned(ptr.cast::<u32>()) };
765
            UPDATE_PRE_VALUE.store(pre as usize, Ordering::SeqCst);
766
        }
767
    }
768

            
769
    #[test]
770
    fn update_fn_fires_once_with_pre_mutation_data() {
771
        UPDATE_CALLS.store(0, Ordering::SeqCst);
772

            
773
        let mut a = RefAny::new(7u32);
774
        let cb: extern "C" fn(*const c_void, usize) = record_update;
775
        a.set_update_fn(cb as usize);
776
        assert_eq!(a.get_update_fn(), cb as usize);
777

            
778
        {
779
            let mut m = a.downcast_mut::<u32>().unwrap();
780
            *m = 9;
781
        }
782
        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
783
        assert_eq!(UPDATE_LEN.load(Ordering::SeqCst), 4);
784
        // The observer saw 7, not 9: it runs BEFORE the borrow is handed out.
785
        assert_eq!(UPDATE_PRE_VALUE.load(Ordering::SeqCst), 7);
786

            
787
        // A wrong-type downcast must not fire it.
788
        assert!(a.downcast_mut::<u64>().is_none());
789
        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
790

            
791
        // A shared borrow is not a mutation -> must not fire it.
792
        assert_eq!(*a.downcast_ref::<u32>().unwrap(), 9);
793
        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
794

            
795
        // A *denied* mutable borrow (shared borrow live on a sibling clone)
796
        // must not fire it either.
797
        let mut b = a.clone();
798
        let r = a.downcast_ref::<u32>().unwrap();
799
        assert!(b.downcast_mut::<u32>().is_none());
800
        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
801
        drop(r);
802

            
803
        // Unregistering stops the observer.
804
        b.set_update_fn(0);
805
        assert!(b.downcast_mut::<u32>().is_some());
806
        assert_eq!(UPDATE_CALLS.load(Ordering::SeqCst), 1);
807
    }
808

            
809
    // ---- predicates ----
810

            
811
    #[test]
812
    fn is_type_true_false_and_extremes() {
813
        let a = RefAny::new(0u32);
814
        let id = a.get_type_id();
815

            
816
        assert!(a.is_type(id));
817
        assert!(!a.is_type(!id)); // every bit flipped -> always a different id
818
        assert!(!a.is_type(id.wrapping_add(1)));
819
        assert!(!a.is_type(RefAny::get_type_id_static::<i32>()));
820
        if id != 0 {
821
            assert!(!a.is_type(0));
822
        }
823
        if id != u64::MAX {
824
            assert!(!a.is_type(u64::MAX));
825
        }
826
    }
827

            
828
    #[test]
829
    fn has_no_copies_transitions() {
830
        let mut a = RefAny::new(1u32);
831
        assert!(a.has_no_copies());
832

            
833
        {
834
            let b = a.clone();
835
            assert!(!a.has_no_copies()); // num_copies == 2
836
            assert!(!b.has_no_copies());
837
        }
838
        assert!(a.has_no_copies()); // clone dropped -> exclusive again
839

            
840
        {
841
            // A live shared borrow (taken via a sibling clone) also disqualifies.
842
            let mut c = a.clone();
843
            let r = c.downcast_ref::<u32>().unwrap();
844
            assert_eq!(*r, 1);
845
            assert!(!a.has_no_copies());
846
        }
847
        assert!(a.has_no_copies());
848

            
849
        {
850
            let mut c = a.clone();
851
            let m = c.downcast_mut::<u32>().unwrap();
852
            assert_eq!(*m, 1);
853
            assert!(!a.has_no_copies());
854
        }
855
        assert!(a.has_no_copies());
856
    }
857

            
858
    #[test]
859
    fn can_serialize_and_can_deserialize_track_the_fn_pointers() {
860
        let mut a = RefAny::new(1u32);
861
        assert!(!a.can_serialize());
862
        assert!(!a.can_deserialize());
863

            
864
        a.set_serialize_fn(1);
865
        assert!(a.can_serialize());
866
        assert!(!a.can_deserialize());
867

            
868
        a.set_deserialize_fn(usize::MAX);
869
        assert!(a.can_serialize());
870
        assert!(a.can_deserialize());
871

            
872
        a.set_serialize_fn(0);
873
        a.set_deserialize_fn(0);
874
        assert!(!a.can_serialize());
875
        assert!(!a.can_deserialize());
876
    }
877

            
878
    // ---- getters ----
879

            
880
    #[test]
881
    fn get_ref_count_tracks_clones_and_borrow_guards() {
882
        let mut a = RefAny::new(5u8);
883
        assert_eq!(a.get_ref_count(), 1);
884

            
885
        let mut b = a.clone();
886
        assert_eq!(a.get_ref_count(), 2);
887
        assert_eq!(b.get_ref_count(), 2);
888

            
889
        {
890
            // The guard clones the RefCount, so it keeps the data alive.
891
            let r = b.downcast_ref::<u8>().unwrap();
892
            assert_eq!(*r, 5);
893
            assert_eq!(a.get_ref_count(), 3);
894
        }
895
        assert_eq!(a.get_ref_count(), 2);
896

            
897
        {
898
            let m = b.downcast_mut::<u8>().unwrap();
899
            assert_eq!(*m, 5);
900
            assert_eq!(a.get_ref_count(), 3);
901
        }
902
        assert_eq!(a.get_ref_count(), 2);
903

            
904
        drop(b);
905
        assert_eq!(a.get_ref_count(), 1);
906
        assert_eq!(*a.downcast_ref::<u8>().unwrap(), 5);
907
    }
908

            
909
    #[test]
910
    fn debug_snapshot_matches_the_live_counters() {
911
        let a = RefAny::new(0x1122_3344u32);
912
        let d = a.sharing_info.debug_get_refcount_copied();
913
        assert_eq!(d.num_copies, 1);
914
        assert_eq!(d.num_refs, 0);
915
        assert_eq!(d.num_mutable_refs, 0);
916
        assert_eq!(d._internal_len, 4);
917
        assert_eq!(d._internal_layout_size, 4);
918
        assert_eq!(d._internal_layout_align, core::mem::align_of::<u32>());
919
        assert_eq!(d.type_id, RefAny::get_type_id_static::<u32>());
920
        assert_eq!(d.type_name.as_str(), "u32");
921
        assert_ne!(d.custom_destructor, 0);
922
        assert_eq!(d.serialize_fn, 0);
923
        assert_eq!(d.deserialize_fn, 0);
924

            
925
        a.sharing_info.increase_ref();
926
        a.sharing_info.increase_refmut();
927
        let d2 = a.sharing_info.debug_get_refcount_copied();
928
        assert_eq!(d2.num_refs, 1);
929
        assert_eq!(d2.num_mutable_refs, 1);
930
        // The first snapshot is a copy, not a view: it must not have changed.
931
        assert_eq!(d.num_refs, 0);
932

            
933
        a.sharing_info.decrease_ref();
934
        a.sharing_info.decrease_refmut();
935
        let d3 = a.sharing_info.debug_get_refcount_copied();
936
        assert_eq!((d3.num_refs, d3.num_mutable_refs), (0, 0));
937

            
938
        // The Debug impl goes through `downcast()` — it must not panic.
939
        assert!(!alloc::format!("{:?}", a.sharing_info).is_empty());
940
    }
941

            
942
    #[test]
943
    fn get_type_name_reports_the_rust_type() {
944
        #[derive(Clone)]
945
        struct AutotestNamed(#[allow(dead_code)] u8);
946

            
947
        let a = RefAny::new(AutotestNamed(1));
948
        let name = a.get_type_name();
949
        assert!(
950
            name.as_str().contains("AutotestNamed"),
951
            "unexpected type name: {}",
952
            name.as_str()
953
        );
954

            
955
        let generic = RefAny::new(Vec::<String>::new());
956
        assert!(generic.get_type_name().as_str().contains("Vec"));
957

            
958
        assert_eq!(RefAny::new(1u32).get_type_name().as_str(), "u32");
959
    }
960

            
961
    // ---- RefCount: construction, downcast, clone/drop balance ----
962

            
963
    #[test]
964
    fn refcount_new_downcast_and_clone_lifecycle() {
965
        let rc = RefCount::new(RefCountInner {
966
            _internal_ptr: core::ptr::null(),
967
            num_copies: AtomicUsize::new(1),
968
            num_refs: AtomicUsize::new(0),
969
            num_mutable_refs: AtomicUsize::new(0),
970
            _internal_len: 0,
971
            _internal_layout_size: 0,
972
            _internal_layout_align: 1,
973
            type_id: 0xDEAD_BEEF,
974
            type_name: AzString::from_const_str("autotest::Synthetic"),
975
            custom_destructor: noop_destructor,
976
            serialize_fn: 0,
977
            deserialize_fn: 0,
978
            update_fn: 0,
979
        });
980
        assert!(!rc.ptr.is_null());
981
        assert!(rc.run_destructor);
982

            
983
        let inner = rc.downcast();
984
        assert_eq!(inner.type_id, 0xDEAD_BEEF);
985
        assert_eq!(inner.type_name.as_str(), "autotest::Synthetic");
986
        assert_eq!(inner._internal_len, 0);
987
        assert!(rc.can_be_shared());
988
        assert!(rc.can_be_shared_mut());
989

            
990
        // Clones must keep the boxed inner alive; the counters must return to 1
991
        // so the final drop frees it exactly once.
992
        let c1 = rc.clone();
993
        assert_eq!(rc.debug_get_refcount_copied().num_copies, 2);
994
        let c2 = c1.clone();
995
        assert_eq!(rc.debug_get_refcount_copied().num_copies, 3);
996
        drop(c2);
997
        drop(c1);
998
        assert_eq!(rc.debug_get_refcount_copied().num_copies, 1);
999
    }
    // The borrow counters must saturate at 0 instead of wrapping to usize::MAX
    // (an unmatched `FooRef_delete` from C would otherwise permanently wedge the
    // runtime borrow checker), and stay usable afterwards.
    #[test]
    fn borrow_counters_saturate_at_zero_and_stay_usable() {
        let mut a = RefAny::new(3i64);
        {
            let rc = &a.sharing_info;
            // 64 unmatched decrements on both counters.
            for _ in 0..64 {
                rc.decrease_ref();
                rc.decrease_refmut();
            }
            let d = rc.debug_get_refcount_copied();
            assert_eq!(d.num_refs, 0);
            assert_eq!(d.num_mutable_refs, 0);
            assert!(rc.can_be_shared());
            assert!(rc.can_be_shared_mut());
            // Many shared borrows coexist, but block a mutable one.
            for _ in 0..256 {
                rc.increase_ref();
            }
            assert_eq!(rc.debug_get_refcount_copied().num_refs, 256);
            assert!(rc.can_be_shared());
            assert!(!rc.can_be_shared_mut());
            for _ in 0..256 {
                rc.decrease_ref();
            }
            assert_eq!(rc.debug_get_refcount_copied().num_refs, 0);
            assert!(rc.can_be_shared_mut());
            // Same for the mutable counter, plus one extra decrement.
            rc.increase_refmut();
            rc.increase_refmut();
            assert!(!rc.can_be_shared());
            rc.decrease_refmut();
            rc.decrease_refmut();
            rc.decrease_refmut();
            assert_eq!(rc.debug_get_refcount_copied().num_mutable_refs, 0);
        }
        // The borrow checker still works after all those underflow attempts.
        assert_eq!(*a.downcast_ref::<i64>().unwrap(), 3);
        assert!(a.downcast_mut::<i64>().is_some());
    }
    // ---- get_type_id_static ----
    // The u64 type ID is the ONLY runtime guard against a wrong-type downcast,
    // so distinct types must not collide (this is what folding ALL TypeId bytes
    // buys us) and it must be stable within a process run.
    #[test]
    fn type_id_static_is_stable_and_collision_free() {
        let ids = [
            RefAny::get_type_id_static::<u8>(),
            RefAny::get_type_id_static::<u16>(),
            RefAny::get_type_id_static::<u32>(),
            RefAny::get_type_id_static::<u64>(),
            RefAny::get_type_id_static::<u128>(),
            RefAny::get_type_id_static::<usize>(),
            RefAny::get_type_id_static::<i8>(),
            RefAny::get_type_id_static::<i16>(),
            RefAny::get_type_id_static::<i32>(),
            RefAny::get_type_id_static::<i64>(),
            RefAny::get_type_id_static::<i128>(),
            RefAny::get_type_id_static::<isize>(),
            RefAny::get_type_id_static::<f32>(),
            RefAny::get_type_id_static::<f64>(),
            RefAny::get_type_id_static::<bool>(),
            RefAny::get_type_id_static::<char>(),
            RefAny::get_type_id_static::<()>(),
            RefAny::get_type_id_static::<String>(),
            RefAny::get_type_id_static::<Vec<u8>>(),
            RefAny::get_type_id_static::<Vec<u16>>(),
            RefAny::get_type_id_static::<[u8; 1]>(),
            RefAny::get_type_id_static::<[u8; 2]>(),
            RefAny::get_type_id_static::<(u8, u8)>(),
            RefAny::get_type_id_static::<(u8, u16)>(),
            RefAny::get_type_id_static::<Option<u8>>(),
            RefAny::get_type_id_static::<Option<u16>>(),
        ];
        for i in 0..ids.len() {
            for j in (i + 1)..ids.len() {
                assert_ne!(ids[i], ids[j], "type id collision between {i} and {j}");
            }
        }
        // Deterministic within a run.
        assert_eq!(RefAny::get_type_id_static::<Vec<u8>>(), ids[18]);
        assert_eq!(RefAny::get_type_id_static::<u8>(), ids[0]);
    }
    // ---- clone / instance ids ----
    #[test]
    fn root_instance_id_is_zero_and_clones_are_distinct() {
        let a = RefAny::new(0u8);
        assert_eq!(a.instance_id, 0);
        let b = a.clone();
        let c = b.clone();
        assert_ne!(b.instance_id, 0);
        assert_ne!(c.instance_id, 0);
        assert_ne!(b.instance_id, c.instance_id);
        assert_eq!(a.get_ref_count(), 3);
    }
    // ---- replace_contents ----
    #[test]
    fn replace_contents_zst_and_value_transitions() {
        #[derive(Clone)]
        struct Zst;
        let mut a = RefAny::new(Zst);
        assert_eq!(a.get_data_len(), 0);
        assert!(a.get_data_ptr().is_null());
        // ZST -> sized: a real allocation must appear.
        assert!(a.replace_contents(RefAny::new(0x4142_4344u32)));
        assert_eq!(a.get_data_len(), 4);
        assert!(!a.get_data_ptr().is_null());
        assert!(a.is_type(RefAny::get_type_id_static::<u32>()));
        assert_eq!(*a.downcast_ref::<u32>().unwrap(), 0x4142_4344);
        // sized -> ZST: the pointer goes back to null, but the ZST still downcasts
        // via a dangling reference; each temporary guard releases its borrow slot
        // on drop, so the exclusive slot is free again afterwards.
        assert!(a.replace_contents(RefAny::new(Zst)));
        assert_eq!(a.get_data_len(), 0);
        assert!(a.get_data_ptr().is_null());
        assert!(a.downcast_ref::<Zst>().is_some());
        assert!(a.downcast_mut::<Zst>().is_some());
        assert!(a.sharing_info.can_be_shared_mut());
    }
    #[test]
    fn replace_contents_is_visible_to_all_clones() {
        let mut a = RefAny::new(1u32);
        let mut b = a.clone();
        assert!(a.replace_contents(RefAny::new(2u32)));
        assert_eq!(*b.downcast_ref::<u32>().unwrap(), 2);
        // The type may change too — every clone sees the new type.
        assert!(a.replace_contents(RefAny::new(String::from("swapped"))));
        assert!(b.downcast_ref::<u32>().is_none());
        assert_eq!(b.downcast_ref::<String>().unwrap().as_str(), "swapped");
        assert!(b.get_type_name().as_str().contains("String"));
        assert_eq!(b.get_type_id(), RefAny::get_type_id_static::<String>());
    }
    #[test]
    fn replace_contents_denied_while_mutably_borrowed() {
        let mut a = RefAny::new(1u32);
        let mut b = a.clone();
        let m = a.downcast_mut::<u32>().unwrap();
        // A live mutable borrow on the shared inner must block the replacement
        // (performing it would free memory the `RefMut` still points at).
        assert!(!b.replace_contents(RefAny::new(2u32)));
        drop(m);
        assert!(b.replace_contents(RefAny::new(2u32)));
        assert_eq!(*b.downcast_ref::<u32>().unwrap(), 2);
    }
    // The serialize/deserialize/update hooks are part of the replaced metadata:
    // after a replacement they describe the NEW value, not the old one.
    #[test]
    fn replace_contents_resets_the_fn_pointers_to_the_new_value() {
        let mut a = RefAny::new(1u32);
        a.set_serialize_fn(3);
        a.set_deserialize_fn(4);
        assert!(a.can_serialize());
        assert!(a.can_deserialize());
        assert!(a.replace_contents(RefAny::new(2u32)));
        assert_eq!(a.get_serialize_fn(), 0);
        assert_eq!(a.get_deserialize_fn(), 0);
        assert_eq!(a.get_update_fn(), 0);
        assert!(!a.can_serialize());
        assert!(!a.can_deserialize());
    }
    // Repeated replacement across changing sizes/alignments must neither leak nor
    // corrupt the payload (Miri checks the alloc/dealloc balance here).
    #[test]
    fn repeated_replace_contents_stays_consistent() {
        let mut a = RefAny::new(String::from("start"));
        for i in 0..16u32 {
            assert!(a.replace_contents(RefAny::new(i)));
            assert_eq!(*a.downcast_ref::<u32>().unwrap(), i);
            assert!(a.replace_contents(RefAny::new(u128::from(i) | (1 << 100))));
            assert_eq!(
                *a.downcast_ref::<u128>().unwrap(),
                u128::from(i) | (1 << 100)
            );
            assert!(a.replace_contents(RefAny::new(String::from("s"))));
        }
        assert_eq!(a.downcast_ref::<String>().unwrap().as_str(), "s");
    }
    // ---- destructor robustness / concurrency ----
    // `default_custom_destructor` is `extern "C"`: a panic from the payload's
    // `Drop` must be caught there, not unwound across the FFI boundary (UB).
    #[cfg(feature = "std")]
    #[test]
    fn panicking_payload_drop_is_contained() {
        struct PanicOnDrop(#[allow(dead_code)] u64);
        impl Drop for PanicOnDrop {
            fn drop(&mut self) {
                panic!("autotest: payload Drop panicked (expected, must be contained)");
            }
        }
        let a = RefAny::new(PanicOnDrop(1));
        drop(a); // must not propagate the panic out of the extern "C" destructor
    }
    // RefAny is Send + Sync: concurrent clone/borrow/drop from several threads
    // must leave the reference count exactly where it started.
    #[cfg(feature = "std")]
    #[test]
    fn concurrent_clone_and_borrow_keeps_the_refcount_balanced() {
        use std::{sync::Arc, thread};
        let shared = Arc::new(RefAny::new(11u32));
        let mut handles = Vec::new();
        for _ in 0..4 {
            let s = Arc::clone(&shared);
            handles.push(thread::spawn(move || {
                for _ in 0..16 {
                    let mut local = (*s).clone();
                    // No thread takes a mutable borrow, so a shared borrow can
                    // never be denied.
                    let r = local
                        .downcast_ref::<u32>()
                        .expect("shared borrow must always succeed here");
                    assert_eq!(*r, 11);
                }
            }));
        }
        for h in handles {
            h.join().expect("worker thread panicked");
        }
        assert_eq!(shared.get_ref_count(), 1);
    }
    /// A RELEASED `RefAny` — one whose `RefCount` has been dropped, which nulls
    /// the pointer on purpose so a second C-side delete is a no-op — must be
    /// safe to INTERROGATE from Rust. It used to abort the process instead:
    /// `get_type_id` walked straight into `RefCount::downcast`'s assertion, and
    /// the release build is `panic = "abort"`, so a stale callback data pointer
    /// took the whole app down on an ordinary focus change (device report,
    /// 2026-09-01). The answer is "nothing here", not death.
    #[test]
    fn a_released_refany_answers_instead_of_aborting() {
        let mut released = RefAny::new(7u32);
        // Take the LIVE `RefCount` out and let it drop: that is the real
        // release path -- it frees the `RefCountInner` and runs the payload's
        // destructor -- and what it leaves behind is exactly what a C-side
        // `AzRefCount_delete` leaves, a null ptr with the decrement already
        // done.
        //
        // This used to stomp `ptr` in place instead. `RefAny::drop` is empty
        // and `RefCount::drop` early-returns on a null ptr, so nothing was ever
        // freed: Miri reported both the `RefCountInner` and the `u32` payload
        // as leaked, correctly, and the Heavy Tests job failed on it the first
        // time it got to run.
        drop(core::mem::replace(
            &mut released.sharing_info,
            RefCount {
                ptr: core::ptr::null(),
                run_destructor: false,
            },
        ));
        assert_eq!(released.get_type_id(), 0, "a released RefAny has no type");
        assert_eq!(released.get_type_name().as_str(), "<released>");
        assert!(
            released.downcast_ref::<u32>().is_none(),
            "there is nothing to borrow",
        );
        assert!(
            released.downcast_mut::<u32>().is_none(),
            "there is nothing to borrow mutably",
        );
        // And the type it really held must not be reachable either.
        assert!(released.downcast_ref::<u8>().is_none());
    }
}