Skip to content

Commit be2d57c

Browse files
committed
Add Arc::as_weak and Rc::as_weak behind new #![feature("rc_as_weak")].
1 parent 5627b9d commit be2d57c

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

library/alloc/src/rc.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,28 @@ impl<T: ?Sized> Rc<T> {
934934
Weak { ptr: this.ptr }
935935
}
936936

937+
/// Convert a reference to an [`Rc`] into a reference to a [`Weak`] of the same type.
938+
///
939+
/// This is a type-only operation; it doesn't modify the inner reference counts.
940+
///
941+
/// # Examples
942+
///
943+
/// ```
944+
/// #![feature(rc_as_weak)]
945+
///
946+
/// use std::rc::{Rc, Weak};
947+
///
948+
/// let five: &Rc<i32> = &Rc::new(5);
949+
///
950+
/// let weak_five: &Weak<i32> = Rc::as_weak(five);
951+
/// ```
952+
#[inline]
953+
#[unstable(feature = "rc_as_weak", issue = "none")]
954+
#[must_use]
955+
pub const fn as_weak<'a>(this: &'a Self) -> &'a Weak<T> {
956+
unsafe { mem::transmute::<&'a Rc<T>, &'a Weak<T>>(this) }
957+
}
958+
937959
/// Gets the number of [`Weak`] pointers to this allocation.
938960
///
939961
/// # Examples

library/alloc/src/sync.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,6 +961,28 @@ impl<T: ?Sized> Arc<T> {
961961
}
962962
}
963963

964+
/// Convert a reference to an [`Arc`] into a reference to a [`Weak`] of the same type.
965+
///
966+
/// This is a type-only operation; it doesn't modify the inner reference counts.
967+
///
968+
/// # Examples
969+
///
970+
/// ```
971+
/// #![feature(rc_as_weak)]
972+
///
973+
/// use std::sync::{Arc, Weak};
974+
///
975+
/// let five: &Arc<i32> = &Arc::new(5);
976+
///
977+
/// let weak_five: &Weak<i32> = Arc::as_weak(five);
978+
/// ```
979+
#[inline]
980+
#[unstable(feature = "rc_as_weak", issue = "none")]
981+
#[must_use]
982+
pub const fn as_weak<'a>(this: &'a Self) -> &'a Weak<T> {
983+
unsafe { mem::transmute::<&'a Arc<T>, &'a Weak<T>>(this) }
984+
}
985+
964986
/// Gets the number of [`Weak`] pointers to this allocation.
965987
///
966988
/// # Safety

0 commit comments

Comments
 (0)