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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Atomic Strong Count.
//!
//! [`Asc`] is a lighter alternative to [`Arc`] for use cases
//! that don't need weak references. It provides shared, thread-safe
//! ownership of heap-allocated data.
//!
//! # Key differences from [`Arc`]
//!
//! * No [`Weak`] references — the allocation is freed as soon as the last
//!   [`Asc`] is dropped. This also means [`Asc`] cannot safely express
//!   reference cycles.
//! * Custom allocators are not yet supported — [`Asc`] always uses the
//!   global allocator. This is blocked on the unstable
//!   [`allocator_api`] feature and will be reconsidered once it stabilizes.
//!
//! # Cycle Warning
//!
//! [`Asc`] does **not** have weak references. Any reference cycle (e.g.,
//! `A → B → A`) will cause a memory leak because the strong count never
//! reaches zero. [`Asc`] is suitable for DAGs and tree structures; for
//! general graphs with back-references, use [`Arc`] with
//! [`Weak`].
//!
//! [`Weak`]: std::sync::Weak
//!
//! # Optional features
//!
//! * **`serde`** — Enables [`serde`] serialization and deserialization.
//! * **`std`** — Enables [`UnwindSafe`] and [`RefUnwindSafe`]
//!   implementations for [`Asc`].
//! * **`unstable`** — Enables [`CoerceUnsized`] and [`DispatchFromDyn`]
//!   implementations, allowing [`Asc<T>`] to be coerced to
//!   [`Asc<dyn Trait>`]. Requires a nightly compiler.
//!
//! # Example
//!
//! ```
//! use asc::Asc;
//!
//! let a: Asc<i32> = Asc::new(42);
//! let b = a.clone();
//!
//! assert_eq!(Asc::strong_count(&a), 2);
//! assert_eq!(*b, 42);
//!
//! // try_unwrap fails while other references exist
//! assert!(Asc::try_unwrap(a.clone()).is_err());
//!
//! drop(b);
//!
//! // try_unwrap succeeds with the last reference
//! let value = Asc::try_unwrap(a).unwrap();
//! assert_eq!(value, 42);
//! ```
//!
//! [`UnwindSafe`]: std::panic::UnwindSafe
//! [`RefUnwindSafe`]: std::panic::RefUnwindSafe
//! [`CoerceUnsized`]: core::ops::CoerceUnsized
//! [`DispatchFromDyn`]: core::ops::DispatchFromDyn
//! [`allocator_api`]: https://github.com/rust-lang/rust/issues/32838
#![deny(
    clippy::all,
    clippy::cargo, //
    clippy::pedantic, //
    clippy::as_conversions,
    clippy::float_arithmetic,
    clippy::arithmetic_side_effects,
    clippy::must_use_candidate,
    clippy::missing_inline_in_public_items,
    clippy::missing_const_for_fn
)]
//
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(
    feature = "unstable",
    feature(unsize, dispatch_from_dyn, coerce_unsized, ptr_metadata)
)]
#![no_std]

extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

use core::alloc::Layout;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::mem;
use core::mem::ManuallyDrop;
use core::mem::MaybeUninit;
use core::ops::Deref;
use core::pin::Pin;
use core::ptr;
use core::ptr::NonNull;
use core::sync::atomic::fence;
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering::{Acquire, Relaxed, Release};

use alloc::boxed::Box;

// Bring Arc into scope for rustdoc intra-doc links.
#[cfg(doc)]
use alloc::sync::Arc;

#[cfg(feature = "unstable")]
use core::marker::Unsize;
#[cfg(feature = "unstable")]
use core::ops::DispatchFromDyn;

#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};

/// Atomic Strong Count.
///
/// [`Asc`] is a lighter alternative to [`Arc`] for use cases that don't
/// need weak references.
pub struct Asc<T: ?Sized> {
    inner: NonNull<Inner<T>>,
    _marker: PhantomData<T>,
}

// Safety: Asc<T> provides the same shared-ownership semantics as Arc<T>.
// When T: Send + Sync, sharing T through Asc across thread boundaries is
// sound because all accesses go through the same atomic reference-counting
// and borrow-checking discipline as std's Arc.
unsafe impl<T: Send + Sync> Send for Asc<T> {}

// Safety: Asc<T> provides the same shared-ownership semantics as Arc<T>.
// &Asc<T> gives access to &T via Deref, so if &T: Sync then &Asc<T>: Sync.
unsafe impl<T: Send + Sync> Sync for Asc<T> {}

#[cfg(feature = "std")]
impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Asc<T> {}

#[cfg(feature = "std")]
impl<T: RefUnwindSafe + ?Sized> RefUnwindSafe for Asc<T> {}

#[cfg(feature = "unstable")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Asc<U>> for Asc<T> {}

#[cfg(feature = "unstable")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Asc<U>> for Asc<T> {}

#[repr(C)]
struct Inner<T: ?Sized> {
    strong: AtomicUsize,
    data: T,
}

unsafe fn box_from_nonnull<T: ?Sized>(p: NonNull<T>) -> Box<T> {
    Box::from_raw(p.as_ptr())
}

fn box_into_nonnull<T>(b: Box<T>) -> NonNull<T> {
    unsafe { NonNull::new_unchecked(Box::into_raw(b)) }
}

#[cfg(not(target_pointer_width = "64"))]
#[cold]
fn critical() -> ! {
    struct Bomb {}

    impl Drop for Bomb {
        fn drop(&mut self) {
            panic!("bomb")
        }
    }

    let _bomb = Bomb {};
    panic!("critical failure")
}

#[cfg(not(target_pointer_width = "64"))]
#[inline(always)]
fn check_overflow(old: usize) {
    if old >= isize::MAX as usize {
        critical()
    }
}

#[cfg(target_pointer_width = "64")]
#[inline(always)]
const fn check_overflow(_old: usize) {}

impl<T> Asc<T> {
    /// Constructs a new `Pin<Asc<T>>`.
    ///
    /// See [`Arc::pin`].
    #[inline]
    #[must_use]
    pub fn pin(data: T) -> Pin<Self> {
        // Safety: Asc::new allocates the data on the heap, so its address
        // is stable for the lifetime of the allocation.
        unsafe { Pin::new_unchecked(Self::new(data)) }
    }

    /// Constructs a new `Asc<T>`.
    ///
    /// See [`Arc::new`].
    #[inline]
    #[must_use]
    pub fn new(data: T) -> Self {
        let inner = Box::new(Inner {
            strong: AtomicUsize::new(1),
            data,
        });
        Self {
            inner: box_into_nonnull(inner),
            _marker: PhantomData,
        }
    }

    /// Returns the inner value if the `Asc` has exactly one strong reference.
    ///
    /// See [`Arc::try_unwrap`].
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` if there are other strong references to the
    /// same allocation.
    #[inline]
    pub fn try_unwrap(this: Self) -> Result<T, Self> {
        let s = this.strong();
        if s.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
            return Err(this);
        }
        // Acquire ordering on successful CAS already provides the
        // necessary acquire semantics for reading the data below.
        unsafe {
            let this = ManuallyDrop::new(this);
            let data = ptr::read(&raw const this.inner.as_ref().data);
            // ManuallyDrop prevents Asc::drop from deallocating Inner<T>.
            // Deallocate the raw memory directly — data was already moved
            // out via ptr::read, so we must not drop T again.
            let layout = Layout::new::<Inner<T>>();
            alloc::alloc::dealloc(this.inner.as_ptr().cast::<u8>(), layout);
            Ok(data)
        }
    }

    /// Returns the inner value if the `Asc` has exactly one strong reference.
    ///
    /// See [`Arc::into_inner`].
    #[inline]
    #[must_use]
    pub fn into_inner(this: Self) -> Option<T> {
        Self::try_unwrap(this).ok()
    }

    /// Reconstructs an `Asc<T>` from a raw pointer previously returned by
    /// [`Asc::into_raw`].
    ///
    /// # Safety
    ///
    /// The pointer must have been obtained from [`Asc::into_raw`]. Each
    /// call to this function consumes one outstanding strong reference;
    /// the pointer must not be used to reconstruct more `Asc`s than the
    /// number of live strong references.
    ///
    /// See [`Arc::from_raw`].
    #[inline]
    #[must_use]
    pub const unsafe fn from_raw(ptr: *const T) -> Self {
        let offset = mem::offset_of!(Inner<T>, data);
        let inner = ptr.cast::<u8>().sub(offset).cast_mut().cast::<Inner<T>>();
        Self {
            inner: NonNull::new_unchecked(inner),
            _marker: PhantomData,
        }
    }

    /// Increments the strong reference count on the `Asc<T>` associated
    /// with the provided pointer by one.
    ///
    /// # Safety
    ///
    /// The pointer must have been obtained from [`Asc::into_raw`] or
    /// [`Asc::as_ptr`], and the underlying allocation must still be
    /// live. Each call to this function creates one additional strong
    /// reference that must be released with
    /// [`Asc::decrement_strong_count`].
    ///
    /// See [`Arc::increment_strong_count`].
    #[inline]
    pub unsafe fn increment_strong_count(ptr: *const T) {
        let offset = mem::offset_of!(Inner<T>, data);
        let inner = ptr.cast::<u8>().sub(offset).cast::<Inner<T>>();
        let strong = unsafe { &(*inner).strong };
        let old = strong.fetch_add(1, Relaxed);
        check_overflow(old);
    }

    /// Decrements the strong reference count on the `Asc<T>` associated
    /// with the provided pointer. If the count reaches zero, the
    /// allocation is freed.
    ///
    /// # Safety
    ///
    /// The pointer must have been obtained from [`Asc::into_raw`] or
    /// [`Asc::as_ptr`], and the underlying allocation must still be
    /// live (unless this call brings the count to zero). Each call
    /// consumes one outstanding strong reference; the caller must
    /// ensure this is paired with a prior
    /// [`Asc::increment_strong_count`] or [`Asc::into_raw`].
    ///
    /// See [`Arc::decrement_strong_count`].
    #[inline]
    pub unsafe fn decrement_strong_count(ptr: *const T) {
        let offset = mem::offset_of!(Inner<T>, data);
        let inner = ptr.cast::<u8>().sub(offset).cast_mut().cast::<Inner<T>>();
        let strong = unsafe { &(*inner).strong };
        if strong.fetch_sub(1, Release) != 1 {
            return;
        }
        fence(Acquire);
        unsafe {
            drop(box_from_nonnull(NonNull::new_unchecked(inner)));
        }
    }

    /// Constructs a new `Asc<MaybeUninit<T>>` with uninitialized contents.
    ///
    /// See [`Arc::new_uninit`].
    #[inline]
    #[must_use]
    pub fn new_uninit() -> Asc<MaybeUninit<T>> {
        let layout = Layout::new::<Inner<MaybeUninit<T>>>();
        let ptr = unsafe { alloc::alloc::alloc(layout) };
        if ptr.is_null() {
            alloc::alloc::handle_alloc_error(layout);
        }
        let ptr = ptr.cast::<Inner<MaybeUninit<T>>>();
        // Initialize the strong count; data remains uninitialized.
        unsafe {
            ptr::addr_of_mut!((*ptr).strong).write(AtomicUsize::new(1));
        }
        Asc {
            inner: unsafe { NonNull::new_unchecked(ptr) },
            _marker: PhantomData,
        }
    }

    /// Constructs a new `Asc<MaybeUninit<T>>` with zeroed contents.
    ///
    /// See [`Arc::new_zeroed`].
    #[inline]
    #[must_use]
    pub fn new_zeroed() -> Asc<MaybeUninit<T>> {
        let layout = Layout::new::<Inner<MaybeUninit<T>>>();
        let ptr = unsafe { alloc::alloc::alloc_zeroed(layout) };
        if ptr.is_null() {
            alloc::alloc::handle_alloc_error(layout);
        }
        let ptr = ptr.cast::<Inner<MaybeUninit<T>>>();
        // alloc_zeroed already zeroed the strong field; reset to 1.
        unsafe {
            ptr::addr_of_mut!((*ptr).strong).write(AtomicUsize::new(1));
        }
        Asc {
            inner: unsafe { NonNull::new_unchecked(ptr) },
            _marker: PhantomData,
        }
    }
}

impl<T> Asc<MaybeUninit<T>> {
    /// Converts an `Asc<MaybeUninit<T>>` to `Asc<T>`.
    ///
    /// # Safety
    ///
    /// The contents must be fully initialized. Calling this when the
    /// contents are not fully initialized causes immediate undefined
    /// behavior.
    ///
    /// See [`Arc::assume_init`].
    #[inline]
    #[must_use]
    pub unsafe fn assume_init(self) -> Asc<T> {
        // MaybeUninit<T> is #[repr(transparent)] over T, so
        // Inner<MaybeUninit<T>> has the same layout as Inner<T>.
        let this = ManuallyDrop::new(self);
        Asc {
            inner: this.inner.cast::<Inner<T>>(),
            _marker: PhantomData,
        }
    }
}

#[cfg(feature = "unstable")]
impl<T> Asc<[MaybeUninit<T>]> {
    /// Converts an `Asc<[MaybeUninit<T>]>` to `Asc<[T]>`.
    ///
    /// # Safety
    ///
    /// Every element of the slice must be fully initialized.
    ///
    /// See [`Arc::assume_init`].
    #[inline]
    #[must_use]
    pub unsafe fn assume_init(self) -> Asc<[T]> {
        let this = ManuallyDrop::new(self);
        let ptr = this.inner.as_ptr();
        let len = ptr::metadata(ptr);
        let inner = ptr::from_raw_parts_mut::<Inner<[T]>>(ptr.cast::<u8>().cast::<()>(), len);
        Asc {
            inner: unsafe { NonNull::new_unchecked(inner) },
            _marker: PhantomData,
        }
    }
}

#[cfg(feature = "unstable")]
impl<T> Asc<[T]> {
    /// Constructs a new `Asc<[MaybeUninit<T>]>` with `len` uninitialized
    /// elements.
    ///
    /// See [`Arc::new_uninit_slice`].
    #[inline]
    #[must_use]
    pub fn new_uninit_slice(len: usize) -> Asc<[MaybeUninit<T>]> {
        let (layout, data_offset) = inner_slice_layout::<T>(len);
        let ptr = unsafe { alloc::alloc::alloc(layout) };
        if ptr.is_null() {
            alloc::alloc::handle_alloc_error(layout);
        }
        let inner = ptr_to_inner_slice::<MaybeUninit<T>>(ptr, data_offset, len);
        unsafe {
            ptr::addr_of_mut!((*inner).strong).write(AtomicUsize::new(1));
        }
        Asc {
            inner: unsafe { NonNull::new_unchecked(inner) },
            _marker: PhantomData,
        }
    }

    /// Constructs a new `Asc<[MaybeUninit<T>]>` with `len` zeroed elements.
    ///
    /// See [`Arc::new_zeroed_slice`].
    #[inline]
    #[must_use]
    pub fn new_zeroed_slice(len: usize) -> Asc<[MaybeUninit<T>]> {
        let (layout, data_offset) = inner_slice_layout::<T>(len);
        let ptr = unsafe { alloc::alloc::alloc_zeroed(layout) };
        if ptr.is_null() {
            alloc::alloc::handle_alloc_error(layout);
        }
        let inner = ptr_to_inner_slice::<MaybeUninit<T>>(ptr, data_offset, len);
        unsafe {
            ptr::addr_of_mut!((*inner).strong).write(AtomicUsize::new(1));
        }
        Asc {
            inner: unsafe { NonNull::new_unchecked(inner) },
            _marker: PhantomData,
        }
    }
}

#[cfg(feature = "unstable")]
fn inner_slice_layout<T>(len: usize) -> (Layout, usize) {
    let strong = Layout::new::<AtomicUsize>();
    let data = Layout::array::<T>(len).expect("capacity overflow");
    strong.extend(data).unwrap()
}

#[cfg(feature = "unstable")]
const fn ptr_to_inner_slice<T>(base: *mut u8, data_offset: usize, len: usize) -> *mut Inner<[T]> {
    // Inner<[T]> is #[repr(C)] with a DST tail [T].
    // Its fat-pointer metadata is the slice length.
    let _ = data_offset; // reserved for future alignment validation
    ptr::from_raw_parts_mut::<Inner<[T]>>(base.cast::<()>(), len)
}

impl<T: ?Sized> Asc<T> {
    const fn strong(&self) -> &AtomicUsize {
        unsafe { &self.inner.as_ref().strong }
    }

    #[inline]
    #[must_use]
    fn shallow_clone(&self) -> Self {
        let s = self.strong();
        let old = s.fetch_add(1, Relaxed);
        check_overflow(old);

        Self {
            inner: self.inner,
            _marker: PhantomData,
        }
    }

    #[inline(never)]
    unsafe fn destroy(&mut self) {
        drop(box_from_nonnull(self.inner));
    }

    /// Returns the number of strong references to this allocation.
    ///
    /// See [`Arc::strong_count`].
    #[inline]
    #[must_use]
    pub fn strong_count(this: &Self) -> usize {
        this.strong().load(Relaxed)
    }

    /// Returns `true` if the two `Asc`s point to the same allocation.
    ///
    /// See [`Arc::ptr_eq`].
    #[inline]
    #[must_use]
    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
        ptr::eq(this.inner.as_ptr(), other.inner.as_ptr())
    }

    /// Returns `true` if this `Asc` has exactly one strong reference.
    ///
    /// This is a snapshot — the result may be stale by the time the
    /// caller reads it, because [`Relaxed`] ordering does not
    /// synchronize with other threads. For safety decisions use
    /// [`Asc::get_mut`] which employs [`Acquire`] ordering.
    ///
    /// See [`Arc::is_unique`].
    #[inline]
    #[must_use]
    pub fn is_unique(this: &Self) -> bool {
        this.strong().load(Relaxed) == 1
    }

    /// Returns a mutable reference to the inner value if no other `Asc`s
    /// point to the same allocation.
    ///
    /// See [`Arc::get_mut`].
    #[inline]
    #[must_use]
    pub fn get_mut(this: &mut Self) -> Option<&mut T> {
        if this.strong().load(Acquire) == 1 {
            // Safety: strong_count == 1 means this is the only Asc
            // pointing to this allocation, so we have exclusive
            // access to the data. Acquire ordering ensures we see
            // all writes from threads that released their references.
            unsafe { Some(Self::get_mut_unchecked(this)) }
        } else {
            None
        }
    }

    /// Returns a mutable reference to the inner value without checking
    /// the reference count.
    ///
    /// # Safety
    ///
    /// The caller must ensure that no other `Asc` pointers to the same
    /// allocation exist.
    ///
    /// See [`Arc::get_mut_unchecked`].
    #[inline]
    #[must_use]
    pub const unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
        &mut this.inner.as_mut().data
    }

    /// Returns a raw pointer to the inner value.
    ///
    /// See [`Arc::as_ptr`].
    #[inline]
    #[must_use]
    pub const fn as_ptr(this: &Self) -> *const T {
        unsafe { ptr::addr_of!(this.inner.as_ref().data) }
    }

    /// Consumes the `Asc` and returns the wrapped raw pointer.
    ///
    /// See [`Arc::into_raw`].
    #[inline]
    #[must_use]
    pub const fn into_raw(this: Self) -> *const T {
        let ptr = Self::as_ptr(&this);
        mem::forget(this);
        ptr
    }
}

impl<T: ?Sized> Deref for Asc<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { &self.inner.as_ref().data }
    }
}

impl<T: ?Sized> Clone for Asc<T> {
    #[inline]
    fn clone(&self) -> Self {
        self.shallow_clone()
    }
}

impl<T: ?Sized> Drop for Asc<T> {
    #[inline]
    fn drop(&mut self) {
        let s = self.strong();
        if s.fetch_sub(1, Release) != 1 {
            return;
        }

        fence(Acquire);
        unsafe { self.destroy() };
    }
}

impl<T: Clone> Asc<T> {
    /// Returns the inner value, cloning it if there are other strong
    /// references.
    ///
    /// See [`Arc::unwrap_or_clone`].
    #[inline]
    #[must_use]
    pub fn unwrap_or_clone(this: Self) -> T {
        Self::try_unwrap(this).unwrap_or_else(|a| T::clone(&a))
    }

    /// Makes a mutable reference to the inner value, cloning the data if
    /// there are other strong references.
    ///
    /// See [`Arc::make_mut`].
    #[inline]
    #[must_use]
    pub fn make_mut(this: &mut Self) -> &mut T {
        let s = this.strong();
        let count = s.load(Acquire);
        if count > 1 {
            *this = Self::new(T::clone(&**this));
        }
        unsafe { &mut this.inner.as_mut().data }
    }
}

impl<T: fmt::Debug + ?Sized> fmt::Debug for Asc<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <T as fmt::Debug>::fmt(&**self, f)
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for Asc<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <T as fmt::Display>::fmt(&**self, f)
    }
}

impl<T: ?Sized> fmt::Pointer for Asc<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&Self::as_ptr(self), f)
    }
}

impl<T: ?Sized + PartialEq> PartialEq for Asc<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}

impl<T: ?Sized + Eq> Eq for Asc<T> {}

impl<T: ?Sized + Hash> Hash for Asc<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

impl<T: ?Sized + PartialOrd> PartialOrd for Asc<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (**self).partial_cmp(&**other)
    }
}

impl<T: ?Sized + Ord> Ord for Asc<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl<T> From<T> for Asc<T> {
    #[inline]
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: Default> Default for Asc<T> {
    #[inline]
    fn default() -> Self {
        Self::new(T::default())
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use super::Asc;

    use serde::{Deserialize, Serialize};

    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    impl<'de, T: Deserialize<'de>> Deserialize<'de> for Asc<T> {
        #[inline]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: ::serde::de::Deserializer<'de>,
        {
            T::deserialize(deserializer).map(Self::new)
        }
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
    impl<T: Serialize> Serialize for Asc<T> {
        #[inline]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: ::serde::ser::Serializer,
        {
            T::serialize(&**self, serializer)
        }
    }
}
#[cfg(test)]
mod tests;