1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Tests for [`Arc`]: cross-thread shareable refcounted smart pointer.

#![allow(clippy::clone_on_ref_ptr, reason = "tests prefer concise method-call form")]
#![allow(clippy::std_instead_of_core, reason = "tests use std for thread/sync primitives")]
#![allow(clippy::unwrap_used, reason = "test code")]

mod common;

use core::cmp::Ordering;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

use multitude::{Arc, Arena};

#[test]
fn cross_thread_arena_arc() {
    let arena = Arena::new();
    let shared: Arc<u64> = arena.alloc_arc(99);
    let s2 = shared.clone();
    let h = std::thread::spawn(move || *s2);
    assert_eq!(*shared, 99);
    assert_eq!(99, h.join().unwrap());

    // Folded coverage_extras::alloc_arc_value_succeeds keeps the direct happy-path assertion.
    let h: Arc<u32> = arena.alloc_arc(7);
    assert_eq!(*h, 7);
}

#[test]
fn shared_alloc_with_drop_type() {
    let arena = Arena::new();
    let counter = std::sync::Arc::new(AtomicUsize::new(0));
    let value = std::sync::Arc::clone(&counter);
    let shared = arena.alloc_arc(value);
    let s2 = shared.clone();
    drop(shared);
    drop(s2);
    drop(arena);
    assert_eq!(std::sync::Arc::strong_count(&counter), 1);
}

#[test]
fn try_alloc_arc_succeeds() {
    let arena = Arena::new();
    let r = arena.try_alloc_arc(99_u32).unwrap();
    assert_eq!(*r, 99);
}

#[test]
fn try_alloc_arc_with_succeeds() {
    let arena = Arena::new();
    let r = arena.try_alloc_arc_with(|| 314_u32).unwrap();
    assert_eq!(*r, 314);
}

#[test]
fn alloc_arc_with_constructs_in_place() {
    let arena = Arena::new();
    let r = arena.alloc_arc_with(|| 271_u32);
    let r2 = r.clone();
    let h = std::thread::spawn(move || *r2);
    assert_eq!(*r, 271);
    assert_eq!(h.join().unwrap(), 271);

    // Folded coverage_extras::alloc_arc_with_closure_succeeds keeps the non-threaded closure path assertion.
    let h: Arc<u64> = arena.alloc_arc_with(|| 42_u64);
    assert_eq!(*h, 42);
}

#[test]
fn alloc_slice_copy_arc_works() {
    let arena = Arena::new();
    let r = arena.alloc_slice_copy_arc([7_u32, 8, 9]);
    let r2 = r.clone();
    let h = std::thread::spawn(move || r2[1]);
    assert_eq!(&*r, &[7, 8, 9]);
    assert_eq!(h.join().unwrap(), 8);

    // Folded coverage_extras::alloc_slice_copy_arc_succeeds keeps the larger direct slice assertion.
    let h: Arc<[u32]> = arena.alloc_slice_copy_arc([1_u32, 2, 3, 4]);
    assert_eq!(&*h, &[1, 2, 3, 4]);
}

#[test]
fn try_alloc_slice_copy_arc_succeeds() {
    let arena = Arena::new();
    let r = arena.try_alloc_slice_copy_arc([7_u32, 8, 9]).unwrap();
    assert_eq!(&*r, &[7, 8, 9]);
}

#[test]
fn as_ptr_returns_value_ptr() {
    let arena = Arena::new();
    let r = arena.alloc_arc(42_u32);
    let p = Arc::as_ptr(&r);
    // SAFETY: ptr is valid while the smart pointer lives.
    assert_eq!(unsafe { *p }, 42);
}

#[test]
fn ptr_eq_distinguishes_handles() {
    let arena = Arena::new();
    let a = arena.alloc_arc(1_u32);
    let b = a.clone();
    let c = arena.alloc_arc(1_u32);
    assert!(Arc::ptr_eq(&a, &b));
    assert!(!Arc::ptr_eq(&a, &c));
}

#[test]
fn debug_display_compare_hash() {
    use std::collections::HashMap;
    use std::hash::{BuildHasher, BuildHasherDefault, Hasher};

    let arena = Arena::new();
    let a = arena.alloc_arc(1_u32);
    let b = arena.alloc_arc(2_u32);
    let a2 = arena.alloc_arc(1_u32);
    assert_eq!(format!("{a:?}"), "1");
    assert_eq!(format!("{a}"), "1");
    assert!(a == a2);
    assert!(a != b);
    assert!(a < b);
    assert_eq!(a.cmp(&b), Ordering::Less);
    assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));

    // Folded mutants_extras::arc_hash_forwards_to_inner / arc_pointer_format_is_non_empty.
    let bh = BuildHasherDefault::<std::collections::hash_map::DefaultHasher>::default();
    let mut h_arc = bh.build_hasher();
    std::hash::Hash::hash(&a, &mut h_arc);
    let arc_hash = h_arc.finish();
    let mut h_inner = bh.build_hasher();
    std::hash::Hash::hash(&1_u32, &mut h_inner);
    let inner_hash = h_inner.finish();
    let h_empty = bh.build_hasher();
    let empty_hash = h_empty.finish();
    assert_eq!(arc_hash, inner_hash, "Arc::hash must forward to inner hash");
    assert_ne!(arc_hash, empty_hash, "Arc::hash must feed bytes (not be a no-op)");
    let mut map: HashMap<Arc<u32>, &'static str> = HashMap::new();
    map.insert(a.clone(), "v");
    assert_eq!(map.get(&a).copied(), Some("v"));
    let s = format!("{a:p}");
    assert!(s.starts_with("0x"), "expected `0x` prefix, got `{s}`");
    assert!(s.len() > 2, "expected non-empty pointer hex digits, got `{s}`");
}

#[test]
fn cross_thread_drop_no_use_after_free() {
    // Stress-test: many short-lived shared smart pointers handed across threads.
    // Validates that the dec_ref-on-non-owner-thread path is sound.
    let arena = Arena::new();
    let handles: std::vec::Vec<_> = (0..100_u32)
        .map(|i| {
            let h = arena.alloc_arc(i);
            std::thread::spawn(move || *h)
        })
        .collect();
    let mut sum = 0_u64;
    for h in handles {
        sum += u64::from(h.join().unwrap());
    }
    assert_eq!(sum, (0..100_u64).sum());

    let _ = AtomicOrdering::SeqCst; // suppress unused-import warning
}

#[test]
fn arena_drop_races_last_shared_handle_drop() {
    // Sanity-check regression for the ArenaInner double-free race that
    // existed before the virtual-arena-reference scheme. The scenario:
    //   - Owner thread drops the Arena.
    //   - Another thread drops the last ArenaArc smart pointer at "the same
    //     time".
    // Pre-fix, both could conclude they were responsible for freeing
    // ArenaInner. With the single-decrementer-wins protocol, atomic
    // serialization guarantees exactly one reclaimer.
    //
    // The exhaustive coverage of this property lives in
    // `tests/loom.rs::loom_arc::arena_drop_concurrent_with_clone_and_drop`
    // (and several adjacent loom models), which explores every atomic
    // interleaving. This test exists only as a complementary smoke test
    // against the *real* code (loom substitutes `cfg(loom)` atomic shims,
    // so it's possible for the loom model to drift from production
    // semantics). A few barrier-synchronized iterations are enough to
    // verify the real `std::sync::atomic` path executes without UB;
    // running thousands of trials doesn't meaningfully improve
    // race-detection probability over what loom already proves
    // exhaustively.
    use std::sync::Barrier;

    for _ in 0..16 {
        let arena = Arena::new();
        let handle: Arc<u64> = arena.alloc_arc(0xDEAD_BEEF);
        let barrier = std::sync::Arc::new(Barrier::new(2));
        let b2 = std::sync::Arc::clone(&barrier);
        let other = std::thread::spawn(move || {
            let _ = b2.wait();
            // Drop the last smart pointer here.
            drop(handle);
        });
        let _ = barrier.wait();
        // Drop the arena here.
        drop(arena);
        other.join().unwrap();
    }
}

// Slice / iterator constructors that produce ArenaArc smart pointers.
// (alloc_slice_copy_arc / try_alloc_slice_copy_arc are tested above.)

#[test]
fn alloc_slice_clone_arc_works() {
    let arena = Arena::new();
    let originals = [std::string::String::from("a"), std::string::String::from("b")];
    let r: Arc<[String]> = arena.alloc_slice_clone_arc(&originals);
    assert_eq!(r.len(), 2);
    assert_eq!(r[0], "a");
    assert_eq!(r[1], "b");
}

#[test]
fn try_alloc_slice_clone_arc_works() {
    let arena = Arena::new();
    let r: Arc<[u32]> = arena.try_alloc_slice_clone_arc([10_u32, 20, 30]).unwrap();
    assert_eq!(&*r, &[10, 20, 30]);
}

#[test]
fn alloc_slice_fill_with_arc_works() {
    let arena = Arena::new();
    let r: Arc<[u64]> = arena.alloc_slice_fill_with_arc(5, |i| (i as u64) * 2);
    assert_eq!(&*r, &[0, 2, 4, 6, 8]);

    // Folded coverage_extras::alloc_slice_fill_with_arc_succeeds keeps the alternate fill pattern.
    let h: Arc<[u32]> = arena.alloc_slice_fill_with_arc(5, |i| u32::try_from(i).unwrap() * 10);
    assert_eq!(&*h, &[0, 10, 20, 30, 40]);
}

#[test]
fn try_alloc_slice_fill_with_arc_works() {
    let arena = Arena::new();
    let r: Arc<[u32]> = arena.try_alloc_slice_fill_with_arc(3, |i| u32::try_from(100 + i).unwrap()).unwrap();
    assert_eq!(&*r, &[100, 101, 102]);
}

#[test]
fn alloc_slice_fill_iter_arc_works() {
    let arena = Arena::new();
    let r: Arc<[i32]> = arena.alloc_slice_fill_iter_arc([0_i32, 1, 2, 3]);
    assert_eq!(&*r, &[0, 1, 2, 3]);

    // Folded coverage_extras::alloc_slice_fill_iter_arc_succeeds keeps the iterator-based happy path.
    let h: Arc<[u32]> = arena.alloc_slice_fill_iter_arc(0_u32..3);
    assert_eq!(&*h, &[0, 1, 2]);
}

#[test]
fn try_alloc_slice_fill_iter_arc_works() {
    let arena = Arena::new();
    let r: Arc<[u32]> = arena.try_alloc_slice_fill_iter_arc([42_u32, 43, 44]).unwrap();
    assert_eq!(&*r, &[42, 43, 44]);
}

#[test]
fn arena_arc_slice_clones_share_chunk() {
    let arena = Arena::new();
    let r: Arc<[u8]> = arena.alloc_slice_copy_arc([1_u8, 2, 3]);
    let r2 = r.clone();
    assert_eq!(&*r, &*r2);
}

#[test]
fn arena_arc_slice_send_to_thread() {
    let arena = Arena::new();
    let r: Arc<[u32]> = arena.alloc_slice_copy_arc([5_u32, 6, 7]);
    let r2 = r.clone();
    let h = std::thread::spawn(move || r2.iter().sum::<u32>());
    assert_eq!(h.join().unwrap(), 18);
    assert_eq!(&*r, &[5, 6, 7]);
}

#[test]
fn arena_arc_outlives_arena_single_thread() {
    // Drives the `teardown_chunk(chunk, false)` branch in ArenaArc::Drop
    // when this is the LAST reference and the arena itself has already
    // been dropped. We construct the scenario deterministically without
    // a thread race so coverage instrumentation observes the path.
    let h: Arc<u64> = {
        let arena = Arena::new();
        arena.alloc_arc(0xDEAD_BEEF)
    };
    // arena is gone; `h` still holds the chunk via virtual refcount.
    assert_eq!(*h, 0xDEAD_BEEF);
    drop(h); // dec_ref → 0 → teardown_chunk(chunk, false).
}

use core::mem::MaybeUninit;

struct DropCount<'a>(&'a AtomicUsize);
impl Drop for DropCount<'_> {
    fn drop(&mut self) {
        let _ = self.0.fetch_add(1, AtomicOrdering::SeqCst);
    }
}

#[test]
fn uninit_arc_dropped_without_init_does_not_run_drop() {
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        {
            let _a: Arc<MaybeUninit<DropCount<'_>>> = arena.alloc_uninit_arc::<DropCount<'_>>();
        }
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 0);
}

#[test]
fn uninit_arc_assume_init_runs_drop_at_chunk_teardown() {
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        let a = arena.alloc_uninit_arc::<DropCount<'_>>();
        // SAFETY: a is the unique handle so we have exclusive write access.
        unsafe {
            let p = Arc::as_ptr(&a).cast::<MaybeUninit<DropCount<'_>>>().cast_mut();
            let _ = (*p).write(DropCount(&counter));
        }
        // SAFETY: just initialized.
        let typed = unsafe { a.assume_init() };
        assert_eq!(counter.load(AtomicOrdering::SeqCst), 0);
        drop(typed);
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 1);
}

#[test]
fn zeroed_arc_produces_zero_bytes() {
    let arena = Arena::new();
    let a = arena.alloc_zeroed_arc::<u64>();
    // SAFETY: zero is a valid bit pattern for u64.
    let a = unsafe { a.assume_init() };
    assert_eq!(*a, 0);
}

// Coverage for the `needs_drop::<T>` branches of the Arc
// uninit/zeroed APIs in `alloc_uninit.rs`. The other tests in this file
// only exercise these with no-drop `u64`, so the slice-path branch
// (which reserves a noop drop entry retargeted by `assume_init`) was
// previously uncovered.
#[test]
fn try_uninit_arc_with_drop_type_uses_slice_path() {
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        let a = arena.try_alloc_uninit_arc::<DropCount<'_>>().expect("must allocate");
        // SAFETY: `a` is the unique handle, so we have exclusive write access.
        unsafe {
            let p = Arc::as_ptr(&a).cast::<MaybeUninit<DropCount<'_>>>().cast_mut();
            (*p).write(DropCount(&counter));
        }
        // SAFETY: just initialized.
        let typed = unsafe { a.assume_init() };
        assert_eq!(counter.load(AtomicOrdering::SeqCst), 0);
        drop(typed);
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 1);
}

#[test]
fn zeroed_arc_with_drop_type_uses_slice_path() {
    // T: Drop. We never `assume_init`, so the noop drop shim runs at
    // chunk teardown (it doesn't dereference the uninitialized bytes),
    // and the real `DropCount::drop` never fires — so the counter
    // stays at 0.
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        let _a: Arc<MaybeUninit<DropCount<'_>>> = arena.alloc_zeroed_arc::<DropCount<'_>>();
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 0);
}

#[test]
fn try_zeroed_arc_with_drop_type_uses_slice_path() {
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        let _a: Arc<MaybeUninit<DropCount<'_>>> = arena.try_alloc_zeroed_arc::<DropCount<'_>>().expect("must allocate");
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 0);
}

#[test]
fn uninit_slice_arc_dropped_without_init_does_not_run_drop() {
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        let _s = arena.alloc_uninit_slice_arc::<DropCount<'_>>(4);
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 0);
}

#[test]
fn uninit_slice_arc_assume_init_runs_drop_per_element() {
    let counter = AtomicUsize::new(0);
    {
        let arena = Arena::new();
        let s = arena.alloc_uninit_slice_arc::<DropCount<'_>>(5);
        // SAFETY: s is the unique handle so we have exclusive write access.
        #[expect(clippy::multiple_unsafe_ops_per_block, reason = "single tightly-coupled write loop")]
        unsafe {
            let base = Arc::as_ptr(&s).cast::<MaybeUninit<DropCount<'_>>>().cast_mut();
            for i in 0..5 {
                let _ = (*base.add(i)).write(DropCount(&counter));
            }
        }
        // SAFETY: all elements just initialized.
        let _typed = unsafe { s.assume_init() };
    }
    assert_eq!(counter.load(AtomicOrdering::SeqCst), 5);
}

#[test]
fn zeroed_slice_arc_produces_zero_bytes() {
    let arena = Arena::new();
    let s = arena.alloc_zeroed_slice_arc::<u32>(6);
    // SAFETY: zeros are a valid bit pattern for u32.
    let s = unsafe { s.assume_init() };
    assert_eq!(&*s, &[0_u32; 6]);
}

#[test]
fn unpin_impl() {
    fn assert_unpin<T: Unpin>() {}
    assert_unpin::<Arc<i32>>();
    #[cfg(feature = "dst")]
    assert_unpin::<Arc<[u8]>>();
}