shared_rc/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3
4extern crate alloc;
5#[cfg(feature = "std")]
6extern crate std;
7
8/// A marker trait for types that can be dropped (*all* types).
9///
10/// Used as `dyn Destruct` to represent truly any type. [`Any`](core::any::Any)
11/// introduces an undesired `'static` bound, [`Drop`] bounds test uselessly for
12/// explicit `Drop` implementations, and [`Sized`] is not `dyn` safe, thus this
13/// trait.
14///
15/// See also the unstable [`std::marker::Destruct`](core::marker::Destruct).
16pub trait Destruct {}
17impl<T: ?Sized> Destruct for T {}
18
19pub use self::{rc::Rc, sync::Arc};
20use core::{
21    borrow::Borrow,
22    cmp::Ordering,
23    fmt,
24    hash::{Hash, Hasher},
25    ops::Deref,
26    ptr,
27};
28#[cfg(feature = "std")]
29use std::{error::Error, panic::UnwindSafe};
30
31macro_rules! make_shared_strong {
32    ($Rc:ident: $($Oibit:ident+)*) => {
33        /// A projecting version of
34        #[doc = concat!(" [`", stringify!($Rc), "`](rc::", stringify!($Rc), ")")]
35        /// which allows owning a containing struct but referencing a field.
36        pub struct $Rc<T: ?Sized, Owner: ?Sized = dyn Destruct $(+$Oibit)*> {
37            owner: rc::$Rc<Owner>,
38            this: ptr::NonNull<T>,
39        }
40
41        unsafe impl<T: ?Sized, Owner: ?Sized> Send for $Rc<T, Owner>
42        where
43            for<'a> &'a T: Send,
44            rc::$Rc<Owner>: Send,
45        {
46        }
47
48        unsafe impl<T: ?Sized, Owner: ?Sized> Sync for $Rc<T, Owner>
49        where
50            for<'a> &'a T: Sync,
51            rc::$Rc<Owner>: Sync,
52        {
53        }
54
55        #[cfg(feature = "std")]
56        impl<T: ?Sized, Owner: ?Sized> UnwindSafe for $Rc<T, Owner>
57        where
58            for<'a> &'a T: UnwindSafe,
59            rc::$Rc<Owner>: UnwindSafe,
60        {
61        }
62
63        impl<T: ?Sized, Owner: ?Sized> Clone for $Rc<T, Owner> {
64            fn clone(&self) -> Self {
65                Self {
66                    owner: self.owner.clone(),
67                    this: self.this,
68                }
69            }
70        }
71
72        impl<'a, T: 'a $(+$Oibit)*> $Rc<T, dyn 'a + Destruct $(+$Oibit)*> {
73            /// Constructs a new
74            #[doc = concat!("`", stringify!($Rc), "<T>`")]
75            /// with erased owner.
76            pub fn new(this: T) -> Self {
77                $Rc::erase_owner($Rc::new_owner(this))
78            }
79        }
80
81        impl<T> $Rc<T, T> {
82            /// Constructs a new
83            #[doc = concat!("`", stringify!($Rc), "<T, T>`")]
84            /// with typed owner.
85            pub fn new_owner(this: T) -> Self {
86                Self::from(this)
87            }
88        }
89
90        impl<'a, T: ?Sized, Owner: 'a $(+$Oibit)*> $Rc<T, Owner> {
91            /// Erases the owning type so projected
92            #[doc = concat!("`", stringify!($Rc), "<T>`")]
93            /// can be used uniformly.
94            pub fn erase_owner(this: Self) -> $Rc<T, dyn 'a + Destruct $(+$Oibit)*> {
95                let Self { owner, this } = this;
96                $Rc { owner, this }
97            }
98        }
99
100        impl<T: ?Sized, Owner: ?Sized> $Rc<T, Owner> {
101            /// Provides a raw pointer to the data.
102            pub fn as_ptr(this: &Self) -> *const T {
103                this.this.as_ptr()
104            }
105
106            /// Creates a new [`Weak`] pointer to this projected field.
107            pub fn downgrade(this: &Self) -> Weak<T, Owner> {
108                let &Self { ref owner, this } = this;
109                let owner = rc::$Rc::downgrade(owner);
110                Weak { owner, this }
111            }
112
113            /// Gets a reference to the owning allocation.
114            ///
115            /// This returns a clone of the owning
116            #[doc = concat!("`", stringify!($Rc), "`,")]
117            /// so it cannot return a unique reference. If you want to take
118            /// unique ownership, use [`into_owner`](Self::into_owner) instead.
119            pub fn owner(this: &Self) -> rc::$Rc<Owner> {
120                rc::$Rc::clone(&this.owner)
121            }
122
123            /// Consumes this projected field and returns the owning allocation.
124            pub fn into_owner(this: Self) -> rc::$Rc<Owner> {
125                this.owner
126            }
127
128            /// Projects this allocation to a field.
129            ///
130            /// Note that the projected field is ***not*** required to actually
131            /// be owned by the owner; it could be any longer-lived reference.
132            pub fn project<U: ?Sized>(
133                this: Self,
134                projection: impl FnOnce(&T) -> &U,
135            ) -> $Rc<U, Owner> {
136                let Self { owner, this } = this;
137                let this = projection(unsafe { this.as_ref() }).into();
138                $Rc { owner, this }
139            }
140
141            /// Returns `true` if the two
142            #[doc = concat!("`", stringify!($Rc), "`s")]
143            /// point to the same field in the same allocated object.
144            ///
145            /// See [`ptr::eq`] for the caveats when comparing `dyn Trait`
146            /// pointers, which this does when the owner type is erased.
147            pub fn ptr_eq(lhs: &Self, rhs: &Self) -> bool {
148                true
149                && rc::$Rc::ptr_eq(&lhs.owner, &rhs.owner)
150                && lhs.this.as_ptr() == rhs.this.as_ptr()
151            }
152        }
153
154        impl<T: ?Sized, Owner: ?Sized> AsRef<T> for $Rc<T, Owner> {
155            fn as_ref(&self) -> &T {
156                unsafe { self.this.as_ref() }
157            }
158        }
159
160        impl<T: ?Sized, Owner: ?Sized> Borrow<T> for $Rc<T, Owner> {
161            fn borrow(&self) -> &T {
162                self.as_ref()
163            }
164        }
165
166        #[cfg(feature = "unsize")]
167        unsafe impl<T, U: ?Sized, Owner: ?Sized> unsize::CoerciblePtr<U> for $Rc<T, Owner> {
168            type Pointee = T;
169            type Output = $Rc<U, Owner>;
170
171            fn as_sized_ptr(&mut self) -> *mut Self::Pointee {
172                self.this.as_ptr()
173            }
174
175            unsafe fn replace_ptr(self, ptr: *mut U) -> Self::Output {
176                $Rc {
177                    owner: self.owner,
178                    this: ptr::NonNull::new_unchecked(ptr),
179                }
180            }
181        }
182
183        #[cfg(feature = "unsize")]
184        impl<T: ?Sized, Owner: ?Sized> $Rc<T, Owner> {
185            /// Convert this pointer with an unsizing coercion
186            /// (e.g. from `T` to `dyn Trait` or `[T; N]` to `[T]`).
187            pub fn unsize<U: ?Sized, F>(
188                this: Self,
189                with: unsize::Coercion<T, U, F>,
190            ) -> $Rc<U, Owner>
191            where
192                T: Sized,
193                F: FnOnce(*const T) -> *const U,
194            {
195                use unsize::CoerceUnsize;
196                let Self { owner, this } = this;
197                let this = this.unsize(with);
198                $Rc { owner, this }
199            }
200
201            /// Convert this pointer with an unsizing coercion of the owner
202            /// (e.g. from `T` to `dyn Trait` or `[T; N]` to `[T]`).
203            pub fn unsize_owner<Pwner: ?Sized, F>(
204                this: Self,
205                with: unsize::Coercion<Owner, Pwner, F>,
206            ) -> $Rc<T, Pwner>
207            where
208                Owner: Sized,
209                F: FnOnce(*const Owner) -> *const Pwner,
210            {
211                use unsize::CoerceUnsize;
212                let Self { owner, this } = this;
213                let owner = unsafe { rc::$Rc::from_raw(rc::$Rc::into_raw(owner).unsize(with)) };
214                $Rc { owner, this }
215            }
216        }
217
218        impl<T: ?Sized, Owner: ?Sized> fmt::Debug for $Rc<T, Owner>
219        where
220            T: fmt::Debug,
221        {
222            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223                fmt::Debug::fmt(&**self, f)
224            }
225        }
226
227        impl<T: Default> Default for $Rc<T, T> {
228            fn default() -> Self {
229                Self::from(T::default())
230            }
231        }
232
233        impl<'a, T: 'a + Default> Default for $Rc<T, dyn 'a + Destruct> {
234            fn default() -> Self {
235                let $Rc { owner, this } = $Rc::<T, T>::default();
236                Self { owner, this }
237            }
238        }
239
240        impl<'a, T: 'a + Default + Send> Default for $Rc<T, dyn 'a + Destruct + Send> {
241            fn default() -> Self {
242                let $Rc { owner, this } = $Rc::<T, T>::default();
243                Self { owner, this }
244            }
245        }
246
247        impl<'a, T: 'a + Default + Send + Sync> Default for $Rc<T, dyn 'a + Destruct + Send + Sync> {
248            fn default() -> Self {
249                let $Rc { owner, this } = $Rc::<T, T>::default();
250                Self { owner, this }
251            }
252        }
253
254        impl<T: ?Sized, Owner: ?Sized> Deref for $Rc<T, Owner> {
255            type Target = T;
256
257            fn deref(&self) -> &T {
258                self.as_ref()
259            }
260        }
261
262        impl<T: ?Sized, Owner: ?Sized> fmt::Display for $Rc<T, Owner>
263        where
264            T: fmt::Display,
265        {
266            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267                fmt::Display::fmt(&**self, f)
268            }
269        }
270
271        impl<T: ?Sized, Owner: ?Sized> Eq for $Rc<T, Owner> where T: Eq {}
272
273        #[cfg(feature = "std")]
274        impl<T: ?Sized, Owner: ?Sized> Error for $Rc<T, Owner>
275        where
276            T: Error,
277        {
278            fn source(&self) -> Option<&(dyn 'static + Error)> {
279                Error::source(&**self)
280            }
281        }
282
283        impl<T, Owner: ?Sized> From<T> for $Rc<T, Owner>
284        where
285            $Rc<T, Owner>: From<$Rc<T, T>>,
286        {
287            fn from(this: T) -> Self {
288                $Rc::<T, T>::from(rc::$Rc::from(this)).into()
289            }
290        }
291
292        impl<T: ?Sized> From<rc::$Rc<T>> for $Rc<T, T> {
293            fn from(owner: rc::$Rc<T>) -> Self {
294                let this = ptr::NonNull::new(rc::$Rc::as_ptr(&owner) as *mut T)
295                    .unwrap();
296                $Rc { owner, this }
297            }
298        }
299
300        impl<T: ?Sized, Owner: ?Sized> From<$Rc<T, Owner>> for rc::$Rc<Owner> {
301            fn from(this: $Rc<T, Owner>) -> Self {
302                this.owner
303            }
304        }
305
306        impl<'a, T: ?Sized, Owner: 'a> From<$Rc<T, Owner>>
307        for $Rc<T, dyn 'a + Destruct> {
308            fn from(this: $Rc<T, Owner>) -> Self {
309                let $Rc { owner, this } = this;
310                $Rc { owner, this }
311            }
312        }
313
314        impl<'a, T: ?Sized, Owner: 'a + Send> From<$Rc<T, Owner>>
315        for $Rc<T, dyn 'a + Destruct + Send> {
316            fn from(this: $Rc<T, Owner>) -> Self {
317                let $Rc { owner, this } = this;
318                $Rc { owner, this }
319            }
320        }
321
322
323        impl<'a, T: ?Sized, Owner: 'a + Send + Sync> From<$Rc<T, Owner>>
324        for $Rc<T, dyn 'a + Destruct + Send + Sync> {
325            fn from(this: $Rc<T, Owner>) -> Self {
326                let $Rc { owner, this } = this;
327                $Rc { owner, this }
328            }
329        }
330
331        impl<T: ?Sized, Owner: ?Sized> Hash for $Rc<T, Owner>
332        where
333            T: Hash,
334        {
335            fn hash<H: Hasher>(&self, state: &mut H) {
336                Hash::hash(&**self, state)
337            }
338        }
339
340        impl<T: ?Sized, Owner: ?Sized> Ord for $Rc<T, Owner>
341        where
342            T: Ord,
343        {
344            fn cmp(&self, other: &Self) -> Ordering {
345                Ord::cmp(&**self, &**other)
346            }
347        }
348
349        impl<T: ?Sized, Owner: ?Sized> PartialEq for $Rc<T, Owner>
350        where
351            T: PartialEq,
352        {
353            fn eq(&self, other: &Self) -> bool {
354                PartialEq::eq(&**self, &**other)
355            }
356        }
357
358        impl<T: ?Sized, Owner: ?Sized> PartialOrd for $Rc<T, Owner>
359        where
360            T: PartialOrd,
361        {
362            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
363                PartialOrd::partial_cmp(&**self, &**other)
364            }
365        }
366
367        impl<T: ?Sized, Owner: ?Sized> fmt::Pointer for $Rc<T, Owner> {
368            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369                fmt::Pointer::fmt(&self.this, f)
370            }
371        }
372    };
373}
374
375macro_rules! make_shared_weak {
376    ($Rc:ident: $($Oibit:ident+)*) => {
377        /// A projecting version of
378        /// [`Weak`](rc::Weak)
379        /// which allows owning a containing struct but referencing a field.
380        pub struct Weak<T: ?Sized, Owner: ?Sized = dyn Destruct $(+$Oibit)*> {
381            owner: rc::Weak<Owner>,
382            this: ptr::NonNull<T>,
383        }
384
385        unsafe impl<T: ?Sized, Owner: ?Sized> Send for Weak<T, Owner>
386        where
387            for<'a> &'a T: Send,
388            rc::Weak<T>: Send,
389        {
390        }
391
392        unsafe impl<T: ?Sized, Owner: ?Sized> Sync for Weak<T, Owner>
393        where
394            for<'a> &'a T: Sync,
395            rc::Weak<T>: Sync,
396        {
397        }
398
399        #[cfg(feature = "std")]
400        impl<T: ?Sized, Owner: ?Sized> UnwindSafe for Weak<T, Owner>
401        where
402            for<'a> &'a T: UnwindSafe,
403            rc::Weak<Owner>: UnwindSafe,
404        {
405        }
406
407        impl<T: ?Sized, Owner: ?Sized> Clone for Weak<T, Owner> {
408            fn clone(&self) -> Self {
409                Self {
410                    owner: self.owner.clone(),
411                    this: self.this,
412                }
413            }
414        }
415
416        impl<'a, T: 'a $(+$Oibit)*> Weak<T, dyn 'a + Destruct $(+$Oibit)*> {
417            /// Constructs a new
418            /// `Weak<T>`
419            /// with erased owner.
420            pub fn new() -> Self {
421                Weak::erase_owner(Weak::<T, T>::new_owner())
422            }
423        }
424
425        impl<T, Owner> Weak<T, Owner> {
426            /// Constructs a new
427            /// `Weak<T, T>`
428            /// with typed owner.
429            pub fn new_owner() -> Self {
430                Self {
431                    owner: rc::Weak::new(),
432                    this: ptr::NonNull::dangling(),
433                }
434            }
435        }
436
437        impl<'a, T: ?Sized, Owner: 'a $(+$Oibit)*> Weak<T, Owner> {
438            /// Erases the owning type so that projected
439            /// `Weak<T>`
440            /// can be used uniformly.
441            pub fn erase_owner(this: Self) -> Weak<T, dyn 'a + Destruct $(+$Oibit)*> {
442                let Self { owner, this } = this;
443                Weak { owner, this }
444            }
445        }
446
447        impl<T: ?Sized, Owner: ?Sized> Weak<T, Owner> {
448            /// Returns a raw pointer to the object `T` pointed to by this
449            /// `Weak<T>`.
450            ///
451            /// The pointer is valid only if there are some strong references.
452            /// The pointer may be dangling, unaligned, or even null otherwise.
453            pub fn as_ptr(&self) -> *const T {
454                self.this.as_ptr()
455            }
456
457            /// Attempts to upgrade the `Weak` pointer to
458            #[doc = concat!("`", stringify!($Rc), "<T>`.")]
459            ///
460            /// Returns [`None`] if no strong references exist.
461            pub fn upgrade(&self) -> Option<$Rc<T, Owner>> {
462                let owner = self.owner.upgrade()?;
463                let this = self.this;
464                Some($Rc { owner, this })
465            }
466
467            /// Gets a reference to the owning allocation.
468            pub fn owner(this: &Self) -> rc::Weak<Owner> {
469                rc::Weak::clone(&this.owner)
470            }
471
472            /// Consumes this projected field, returning the owning allocation.
473            pub fn into_owner(this: Self) -> rc::Weak<Owner> {
474                this.owner
475            }
476
477            /// Projects this allocation to a field.
478            ///
479            /// If no strong references exist, the closure will not be called.
480            pub fn project<U: Sized>(
481                this: Self,
482                projection: impl FnOnce(&T) -> &U,
483            ) -> Weak<U, Owner> {
484                let Self { owner, this } = this;
485                let this = match owner.upgrade() {
486                    None => ptr::NonNull::dangling(),
487                    Some(_guard) => projection(unsafe { this.as_ref() }).into(),
488                };
489                Weak { owner, this }
490            }
491
492            /// Returns `true` if the two `Weak`s point to the same field in
493            /// the same allocated object, or if both don't point to anything
494            /// (i.e. because they were created with `Weak::new()`).
495            ///
496            /// See [`ptr::eq`] for the caveats when comparing `dyn Trait`
497            /// pointers, which this does when the owner type is erased.
498            pub fn ptr_eq(lhs: &Self, rhs: &Self) -> bool {
499                true
500                && rc::Weak::ptr_eq(&lhs.owner, &rhs.owner)
501                && lhs.this.as_ptr() == rhs.this.as_ptr()
502            }
503        }
504
505        #[cfg(feature = "unsize")]
506        unsafe impl<T, U: ?Sized, Owner: ?Sized> unsize::CoerciblePtr<U> for Weak<T, Owner> {
507            type Pointee = T;
508            type Output = Weak<U, Owner>;
509
510            fn as_sized_ptr(&mut self) -> *mut Self::Pointee {
511                self.this.as_ptr()
512            }
513
514            unsafe fn replace_ptr(self, ptr: *mut U) -> Self::Output {
515                Weak {
516                    owner: self.owner,
517                    this: ptr::NonNull::new_unchecked(ptr),
518                }
519            }
520        }
521
522        #[cfg(feature = "unsize")]
523        impl<T: ?Sized, Owner: ?Sized> Weak<T, Owner> {
524            /// Convert this pointer with an unsizing coercion
525            /// (e.g. from `T` to `dyn Trait` or `[T; N]` to `[T]`).
526            pub fn unsize<U: ?Sized, F>(
527                this: Self,
528                with: unsize::Coercion<T, U, F>,
529            ) -> Weak<U, Owner>
530            where
531                T: Sized,
532                F: FnOnce(*const T) -> *const U,
533            {
534                use unsize::CoerceUnsize;
535                let Self { owner, this } = this;
536                let this = this.unsize(with);
537                Weak { owner, this }
538            }
539
540            /// Convert this pointer with an unsizing coercion of the owner
541            /// (e.g. from `T` to `dyn Trait` or `[T; N]` to `[T]`).
542            pub fn unsize_owner<Pwner: ?Sized, F>(
543                this: Self,
544                with: unsize::Coercion<Owner, Pwner, F>,
545            ) -> Weak<T, Pwner>
546            where
547                Owner: Sized,
548                F: FnOnce(*const Owner) -> *const Pwner,
549            {
550                use unsize::CoerceUnsize;
551                let Self { owner, this } = this;
552                let owner = unsafe { rc::Weak::from_raw(rc::Weak::into_raw(owner).unsize(with)) };
553                Weak { owner, this }
554            }
555        }
556
557        impl<T: ?Sized, Owner: ?Sized> fmt::Debug for Weak<T, Owner>
558        where
559            T: fmt::Debug,
560        {
561            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562                write!(f, "(Weak)")
563            }
564        }
565
566        impl<T, Owner> Default for Weak<T, Owner>
567        {
568            fn default() -> Self {
569                Self {
570                    owner: rc::Weak::new(),
571                    this: ptr::NonNull::dangling(),
572                }
573            }
574        }
575
576        impl<'a, T: 'a> Default for Weak<T, dyn 'a + Destruct>
577        {
578            fn default() -> Self {
579                Self {
580                    owner: rc::Weak::<()>::new(),
581                    this: ptr::NonNull::dangling(),
582                }
583            }
584        }
585
586        impl<'a, T: 'a> Default for Weak<T, dyn 'a + Destruct + Send>
587        {
588            fn default() -> Self {
589                Self {
590                    owner: rc::Weak::<()>::new(),
591                    this: ptr::NonNull::dangling(),
592                }
593            }
594        }
595
596        impl<'a, T: 'a> Default for Weak<T, dyn 'a + Destruct + Send + Sync>
597        {
598            fn default() -> Self {
599                Self {
600                    owner: rc::Weak::<()>::new(),
601                    this: ptr::NonNull::dangling(),
602                }
603            }
604        }
605
606        impl<T> From<rc::Weak<T>> for Weak<T, T> {
607            fn from(owner: rc::Weak<T>) -> Self {
608                let this = ptr::NonNull::new(owner.as_ptr() as *mut T)
609                    .unwrap_or(ptr::NonNull::dangling());
610                Self { owner, this }
611            }
612        }
613
614        impl<T: ?Sized, Owner: ?Sized> From<Weak<T, Owner>> for rc::Weak<Owner> {
615            fn from(this: Weak<T, Owner>) -> Self {
616                this.owner
617            }
618        }
619
620        impl<'a, T: ?Sized, Owner: 'a> From<Weak<T, Owner>>
621        for Weak<T, dyn 'a + Destruct> {
622            fn from(this: Weak<T, Owner>) -> Self {
623                let Weak { owner, this } = this;
624                Weak { owner, this }
625            }
626        }
627
628        impl<'a, T: ?Sized, Owner: 'a + Send> From<Weak<T, Owner>>
629        for Weak<T, dyn 'a + Destruct + Send> {
630            fn from(this: Weak<T, Owner>) -> Self {
631                let Weak { owner, this } = this;
632                Weak { owner, this }
633            }
634        }
635
636        impl<'a, T: ?Sized, Owner: 'a + Send + Sync> From<Weak<T, Owner>>
637        for Weak<T, dyn 'a + Destruct + Send + Sync> {
638            fn from(this: Weak<T, Owner>) -> Self {
639                let Weak { owner, this } = this;
640                Weak { owner, this }
641            }
642        }
643    };
644}
645
646macro_rules! make_shared_rc {
647    ($Rc:ident: $($Oibit:ident+)*) => {
648        make_shared_strong!($Rc: $($Oibit+)*);
649        make_shared_weak!($Rc: $($Oibit+)*);
650    };
651}
652
653/// Thread-safe reference-counting pointers.
654///
655/// See the [`Arc`] documentation for more details.
656pub mod sync {
657    use {super::*, alloc::sync as rc};
658    make_shared_rc!(Arc: Send+Sync+);
659}
660
661/// Single-threaded reference-counting pointers.
662///
663/// See the [`Rc`] documentation for more details.
664pub mod rc {
665    use {super::*, alloc::rc};
666    make_shared_rc!(Rc:);
667}