asc 0.3.0

Atomic Strong Count
Documentation
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
use super::Asc;

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;

#[test]
fn clone_and_drop() {
    let a = Asc::new(String::from("hello"));
    let a1 = a.shallow_clone();
    let a2 = Asc::clone(&a);

    assert_eq!(&*a, "hello");

    drop(a1);
    drop(a);
    drop(a2);
}

#[test]
fn strong_count_basic() {
    let a = Asc::new(42i32);
    assert_eq!(Asc::strong_count(&a), 1);

    let b = a.clone();
    assert_eq!(Asc::strong_count(&a), 2);
    assert_eq!(Asc::strong_count(&b), 2);

    drop(b);
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn ptr_eq_same() {
    let a = Asc::new(1);
    let b = a.clone();
    assert!(Asc::ptr_eq(&a, &b));

    let c = Asc::new(1);
    assert!(!Asc::ptr_eq(&a, &c));
}

#[test]
fn try_unwrap_success() {
    let a = Asc::new(42);
    let val = Asc::try_unwrap(a).unwrap();
    assert_eq!(val, 42);
}

#[test]
fn try_unwrap_failure() {
    let a = Asc::new(42);
    let _b = a.clone();
    let result = Asc::try_unwrap(a);
    assert!(result.is_err());
    // Returns the Asc back on failure
    let a = result.unwrap_err();
    assert_eq!(*a, 42);
}

#[test]
fn into_inner_unique() {
    let a = Asc::new("data");
    assert_eq!(Asc::into_inner(a), Some("data"));
}

#[test]
fn into_inner_shared() {
    let a = Asc::new("data");
    let _b = a.clone();
    assert_eq!(Asc::into_inner(a), None);
}

#[test]
fn unwrap_or_clone_unique() {
    let a = Asc::new(String::from("hello"));
    let s = Asc::unwrap_or_clone(a);
    assert_eq!(s, "hello");
}

#[test]
fn unwrap_or_clone_shared() {
    let a = Asc::new(String::from("hello"));
    let _b = a.clone();
    let s = Asc::unwrap_or_clone(a);
    assert_eq!(s, "hello");
}

// roundtrip through raw pointer creates a temporary &Inner<T> in
// as_ptr; miri Stacked Borrows rejects re-deriving a reference from
// the raw pointer in from_raw. This is a known limitation of the
// Stacked Borrows model and does not indicate a real bug.
#[test]
#[cfg_attr(miri, ignore)]
fn into_raw_from_raw_roundtrip() {
    let a = Asc::new(42i32);
    let ptr = Asc::into_raw(a);
    let a = unsafe { Asc::from_raw(ptr) };
    assert_eq!(*a, 42);
}

#[test]
fn as_ptr_borrowed() {
    let a = Asc::new(7u32);
    let ptr = Asc::as_ptr(&a);
    // as_ptr provides a borrowed pointer — the original Asc still owns
    // the allocation. Reading through the pointer is safe while a lives.
    assert_eq!(unsafe { *ptr }, 7);
    assert_eq!(*a, 7);
}

// miri: see comment on into_raw_from_raw_roundtrip.
#[test]
#[cfg_attr(miri, ignore)]
fn from_raw_high_alignment() {
    #[repr(align(64))]
    struct Aligned(u8);

    let a = Asc::new(Aligned(42));
    let ptr = Asc::into_raw(a);
    let a = unsafe { Asc::from_raw(ptr) };
    assert_eq!(a.0, 42);
}

// miri: into_raw invalidates the original reference tag; creating
// &(*inner).strong from the raw pointer hits the Stacked Borrows
// limitation (same as into_raw_from_raw_roundtrip).
#[test]
#[cfg_attr(miri, ignore)]
fn increment_decrement_strong_count() {
    let a = Asc::new(42i32);
    let ptr = Asc::into_raw(a);

    // Increment: now there are 2 logical references
    unsafe { Asc::increment_strong_count(ptr) };

    // Reconstruct: should have count 2
    let a = unsafe { Asc::from_raw(ptr) };
    assert_eq!(Asc::strong_count(&a), 2);
    assert_eq!(*a, 42);

    // Decrement one reference
    unsafe { Asc::decrement_strong_count(Asc::as_ptr(&a)) };
    assert_eq!(Asc::strong_count(&a), 1);

    // Decrement the last reference: allocation freed
    let ptr = Asc::into_raw(a);
    unsafe { Asc::decrement_strong_count(ptr) };
    // If we reach here without double-free, the test passes
}

// miri: &(*inner).strong retags through a pointer derived from
// as_ptr (same Stacked Borrows limitation as from_raw roundtrip).
#[test]
#[cfg_attr(miri, ignore)]
fn increment_strong_count_via_as_ptr() {
    // Uses as_ptr (not into_raw) so the Asc stays alive during the test.
    let a = Asc::new(7u32);
    let ptr = Asc::as_ptr(&a);
    unsafe { Asc::increment_strong_count(ptr) };
    assert_eq!(Asc::strong_count(&a), 2);
    // Clean up the extra reference without deallocating
    unsafe { Asc::decrement_strong_count(ptr) };
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn is_unique_basic() {
    let a = Asc::new(1);
    assert!(Asc::is_unique(&a));
    let b = a.clone();
    assert!(!Asc::is_unique(&a));
    assert!(!Asc::is_unique(&b));
    drop(b);
    assert!(Asc::is_unique(&a));
}

#[test]
fn get_mut_unique() {
    let mut a = Asc::new(10i32);
    {
        let val = Asc::get_mut(&mut a).unwrap();
        *val = 20;
    }
    assert_eq!(*a, 20);
}

#[test]
fn get_mut_shared() {
    let mut a = Asc::new(10i32);
    let _b = a.clone();
    assert!(Asc::get_mut(&mut a).is_none());
}

#[test]
fn make_mut_unique() {
    let mut a = Asc::new(5i32);
    *Asc::make_mut(&mut a) = 10;
    assert_eq!(*a, 10);
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn make_mut_shared_clones() {
    let mut a = Asc::new(5i32);
    let _b = a.clone();
    assert_eq!(Asc::strong_count(&a), 2);

    // make_mut should clone-on-write (allocate new inner)
    *Asc::make_mut(&mut a) = 10;
    assert_eq!(*a, 10);
    // Now a should have its own allocation with count 1
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn pin_basic() {
    let pinned = Asc::pin(42i32);
    assert_eq!(*pinned, 42);
    // Cloning a pinned Asc should work
    let _clone = pinned.clone();
}

#[test]
fn deref() {
    let a = Asc::new(100);
    assert_eq!(*a, 100);
}

#[test]
fn partial_eq() {
    let a = Asc::new(1);
    let b = Asc::new(1);
    let c = Asc::new(2);
    assert_eq!(a, b);
    assert_ne!(a, c);
}

#[test]
fn eq_trait() {
    fn assert_eq_trait<T: core::cmp::Eq>(_t: &T) {}
    let a = Asc::new(1);
    assert_eq_trait(&a);
}

#[test]
fn hash() {
    use core::hash::{BuildHasher, Hasher};

    #[derive(Default)]
    struct SimpleHasher(u64);

    impl Hasher for SimpleHasher {
        fn finish(&self) -> u64 {
            self.0
        }
        fn write(&mut self, bytes: &[u8]) {
            for &b in bytes {
                self.0 = self.0.wrapping_mul(31).wrapping_add(u64::from(b));
            }
        }
    }

    #[derive(Default)]
    struct SimpleBuildHasher;

    impl BuildHasher for SimpleBuildHasher {
        type Hasher = SimpleHasher;
        fn build_hasher(&self) -> SimpleHasher {
            SimpleHasher::default()
        }
    }

    let bh = SimpleBuildHasher;
    let a = Asc::new(1);
    let b = Asc::new(1);
    let c = Asc::new(2);
    assert_eq!(bh.hash_one(&a), bh.hash_one(&b));
    assert_ne!(bh.hash_one(&a), bh.hash_one(&c));
}

#[test]
fn ord_as_map_key() {
    let mut map = BTreeMap::new();
    map.insert(Asc::new(1), "one");
    map.insert(Asc::new(2), "two");
    assert_eq!(map.get(&Asc::new(1)), Some(&"one"));
    assert_eq!(map.get(&Asc::new(2)), Some(&"two"));
}

#[test]
fn partial_ord_and_ord() {
    let a = Asc::new(1);
    let b = Asc::new(2);
    assert!(a < b);
    assert!(b > a);
    assert_eq!(a.cmp(&b), core::cmp::Ordering::Less);
}

#[test]
fn display() {
    let a = Asc::new(42);
    assert_eq!(format!("{a}"), "42");
}

#[test]
fn pointer_fmt() {
    let a = Asc::new(1);
    let s = format!("{a:p}");
    let expected = format!("{:p}", Asc::as_ptr(&a));
    assert_eq!(s, expected);
}

#[test]
fn from_trait() {
    let a: Asc<i32> = 42.into();
    assert_eq!(*a, 42);
}

#[test]
fn default_trait() {
    let a: Asc<i32> = Asc::default();
    assert_eq!(*a, 0);
}

#[test]
fn debug() {
    let a = Asc::new(7);
    assert_eq!(format!("{a:?}"), "7");
}

#[test]
fn send_sync() {
    fn assert_send<T: Send>(_t: &T) {}
    fn assert_sync<T: Sync>(_t: &T) {}
    let a = Asc::new(1);
    assert_send(&a);
    assert_sync(&a);
}

#[test]
fn try_unwrap_after_make_mut() {
    let mut a = Asc::new(String::from("hello"));
    let _b = a.clone();
    // This clones into a new allocation
    Asc::make_mut(&mut a).push_str(" world");
    // Now a has count 1 in its own allocation
    let s = Asc::try_unwrap(a).unwrap();
    assert_eq!(s, "hello world");
}

#[test]
fn test_vec_of_asc() {
    let items: Vec<Asc<i32>> = (0..5).map(Asc::new).collect();
    let clones: Vec<Asc<i32>> = items.iter().map(Asc::clone).collect();
    assert_eq!(items.len(), clones.len());
    for (a, b) in items.iter().zip(&clones) {
        assert!(Asc::ptr_eq(a, b));
    }
}

#[test]
fn drop_behavior() {
    // Verify that dropping doesn't panic and strong_count decreases
    let a = Asc::new(());
    let b = a.clone();
    let c = a.clone();
    assert_eq!(Asc::strong_count(&a), 3);
    drop(b);
    assert_eq!(Asc::strong_count(&a), 2);
    drop(c);
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn zero_sized_type() {
    let a = Asc::new(());
    let b = a.clone();
    assert_eq!(Asc::strong_count(&a), 2);
    assert!(Asc::ptr_eq(&a, &b));
    drop(b);
    Asc::try_unwrap(a).unwrap();
}

#[test]
fn get_mut_unchecked_direct() {
    let mut a = Asc::new(5i32);
    // Safety: a is the only reference.
    unsafe {
        *Asc::get_mut_unchecked(&mut a) = 15;
    }
    assert_eq!(*a, 15);
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn make_mut_zero_sized() {
    let mut a = Asc::new(());
    let _b = a.clone();
    assert_eq!(Asc::strong_count(&a), 2);
    // make_mut clones into a new allocation since count > 1
    let _val = Asc::make_mut(&mut a);
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn try_unwrap_zero_sized_shared() {
    let a = Asc::new(());
    let _b = a.clone();
    let result = Asc::try_unwrap(a);
    assert!(result.is_err());
    let a = result.unwrap_err();
    assert_eq!(*a, ());
    drop(a);
}

#[test]
fn make_mut_preserves_value() {
    let mut a = Asc::new(String::from("original"));
    let b = a.clone();
    Asc::make_mut(&mut a).push_str(" modified");
    // b still has the original value
    assert_eq!(&*b, "original");
    // a has the modified value in a new allocation
    assert_eq!(&*a, "original modified");
}

#[cfg(feature = "serde")]
mod serde_tests {
    use super::Asc;
    use alloc::string::String;
    use alloc::vec;
    use alloc::vec::Vec;

    #[test]
    fn serialize_basic() {
        let a = Asc::new(42i32);
        let json = serde_json::to_string(&a).unwrap();
        assert_eq!(json, "42");
    }

    #[test]
    fn deserialize_basic() {
        let a: Asc<i32> = serde_json::from_str("42").unwrap();
        assert_eq!(*a, 42);
    }

    #[test]
    fn roundtrip_json() {
        let a = Asc::new(String::from("hello"));
        let json = serde_json::to_string(&a).unwrap();
        let b: Asc<String> = serde_json::from_str(&json).unwrap();
        assert_eq!(*a, *b);
    }

    #[test]
    fn serialize_complex() {
        let a = Asc::new(vec![1, 2, 3]);
        let json = serde_json::to_string(&a).unwrap();
        assert_eq!(json, "[1,2,3]");
    }

    #[test]
    fn deserialize_complex() {
        let a: Asc<Vec<i32>> = serde_json::from_str("[4,5,6]").unwrap();
        assert_eq!(*a, vec![4, 5, 6]);
    }

    #[test]
    fn serialize_shared() {
        let a = Asc::new(10);
        let _b = a.clone();
        let json = serde_json::to_string(&a).unwrap();
        assert_eq!(json, "10");
    }

    #[test]
    fn serialize_zero_sized() {
        let a = Asc::new(());
        let json = serde_json::to_string(&a).unwrap();
        assert_eq!(json, "null");
    }
}

#[cfg(feature = "unstable")]
mod dst_tests {
    use super::Asc;
    use alloc::format;
    use alloc::string::String;
    use core::fmt::Debug;
    use core::mem::MaybeUninit;

    #[test]
    fn slice_deref_clone_drop() {
        let a: Asc<[i32]> = Asc::new([1, 2, 3]);
        assert_eq!(&*a, &[1, 2, 3]);

        let b = a.clone();
        assert_eq!(Asc::strong_count(&a), 2);
        assert!(Asc::ptr_eq(&a, &b));

        drop(b);
        assert_eq!(Asc::strong_count(&a), 1);
    }

    #[test]
    fn slice_debug() {
        let a: Asc<[i32]> = Asc::new([10, 20]);
        assert_eq!(format!("{a:?}"), "[10, 20]");
    }

    #[test]
    fn slice_partial_eq() {
        let a: Asc<[i32]> = Asc::new([1, 2]);
        let b: Asc<[i32]> = Asc::new([1, 2]);
        let c: Asc<[i32]> = Asc::new([3, 4]);
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    // miri: into_raw without from_raw leaks the allocation (from_raw
    // is Sized-only, so DST reconstruction is not possible).
    #[test]
    #[cfg_attr(miri, ignore)]
    fn slice_as_ptr_into_raw() {
        let a: Asc<[i32]> = Asc::new([7, 8, 9]);
        let ptr = Asc::as_ptr(&a);
        assert_eq!(unsafe { &*ptr }, &[7, 8, 9]);

        let ptr2 = Asc::into_raw(a);
        assert_eq!(unsafe { &*ptr2 }, &[7, 8, 9]);
        // from_raw is Sized-only for Asc; leak the allocation.
    }

    #[test]
    fn trait_object_deref_clone_drop() {
        let a: Asc<dyn Debug> = Asc::new(String::from("hello"));
        assert_eq!(format!("{a:?}"), "\"hello\"");

        let b = a.clone();
        assert_eq!(Asc::strong_count(&a), 2);
        drop(b);
        assert_eq!(Asc::strong_count(&a), 1);
    }

    #[test]
    fn trait_object_pointer_fmt() {
        let a: Asc<dyn Debug> = Asc::new(42i32);
        let s = format!("{a:p}");
        let expected = format!("{:p}", Asc::as_ptr(&a));
        assert_eq!(s, expected);
    }

    // miri: from_raw_parts_mut for Inner<[MaybeUninit<T>]> fat pointer
    // construction is subject to the same Stacked Borrows limitation.
    #[test]
    #[cfg_attr(miri, ignore)]
    fn new_uninit_slice_assume_init() {
        let mut uninit: Asc<[MaybeUninit<i32>]> = Asc::new_uninit_slice(3);
        assert_eq!(Asc::strong_count(&uninit), 1);

        // Initialize via get_mut
        let mu = Asc::get_mut(&mut uninit).unwrap();
        mu[0].write(10);
        mu[1].write(20);
        mu[2].write(30);

        let init: Asc<[i32]> = unsafe { uninit.assume_init() };
        assert_eq!(&*init, &[10, 20, 30]);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn new_zeroed_slice_assume_init() {
        let zeroed: Asc<[MaybeUninit<u64>]> = Asc::new_zeroed_slice(4);
        let init: Asc<[u64]> = unsafe { zeroed.assume_init() };
        assert_eq!(&*init, &[0u64, 0, 0, 0]);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn new_uninit_slice_zst() {
        let mut uninit: Asc<[MaybeUninit<()>]> = Asc::new_uninit_slice(5);
        Asc::get_mut(&mut uninit).unwrap()[2].write(());
        let init: Asc<[()]> = unsafe { uninit.assume_init() };
        assert_eq!(init.len(), 5);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn new_uninit_slice_zero_len() {
        let uninit: Asc<[MaybeUninit<i32>]> = Asc::new_uninit_slice(0);
        assert_eq!(Asc::strong_count(&uninit), 1);
        // Zero-length slices are valid: only the header (strong field)
        // is allocated, no data elements.
        drop(uninit);
    }
}

#[cfg(feature = "std")]
mod thread_tests {
    use super::Asc;
    use alloc::vec::Vec;
    use std::thread;

    #[test]
    fn send_to_another_thread() {
        let a = Asc::new(42i32);
        let handle = thread::spawn(move || {
            assert_eq!(*a, 42);
            Asc::strong_count(&a)
        });
        let count = handle.join().unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn clone_across_threads() {
        let a = Asc::new(0i32);
        let b = a.clone();
        let handle = thread::spawn(move || {
            assert_eq!(*b, 0);
        });
        handle.join().unwrap();
        assert_eq!(*a, 0);
        assert_eq!(Asc::strong_count(&a), 1);
    }

    #[test]
    fn concurrent_clone_drop() {
        let a = Asc::new(());
        let n = 8;
        let mut handles = Vec::new();
        for _ in 0..n {
            let a = a.clone();
            handles.push(thread::spawn(move || {
                let _a = a;
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(Asc::strong_count(&a), 1);
        // If concurrent clone/drop had a race, we'd see wrong count or UB
    }
}

#[test]
fn new_uninit_assume_init() {
    let mut five = Asc::<i32>::new_uninit();
    Asc::get_mut(&mut five).unwrap().write(5);
    let five = unsafe { five.assume_init() };
    assert_eq!(*five, 5);
}

#[test]
fn new_zeroed_assume_init() {
    let zeroed = Asc::<u64>::new_zeroed();
    let zeroed = unsafe { zeroed.assume_init() };
    assert_eq!(*zeroed, 0u64);
}

#[test]
fn new_uninit_zst() {
    let mut zst = Asc::<()>::new_uninit();
    Asc::get_mut(&mut zst).unwrap().write(());
    let zst = unsafe { zst.assume_init() };
    assert_eq!(*zst, ());
}

#[test]
fn new_zeroed_drop_behavior() {
    let a = Asc::<i32>::new_zeroed();
    let b = a.clone();
    assert_eq!(Asc::strong_count(&a), 2);
    drop(b);
    assert_eq!(Asc::strong_count(&a), 1);
}

#[test]
fn new_uninit_drop_without_init() {
    // Dropping an uninitialized MaybeUninit<i32> is safe because
    // MaybeUninit does not run Drop on the inner value.
    let _a = Asc::<i32>::new_uninit();
    let _b = Asc::<String>::new_uninit();
}