Skip to content

Commit f5e6d16

Browse files
committed
Add tracking issue and impl for Rc.
1 parent 0602fb0 commit f5e6d16

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

library/alloc/src/rc.rs

+35
Original file line numberDiff line numberDiff line change
@@ -1203,6 +1203,41 @@ impl<T: Clone> Rc<T> {
12031203
// reference to the allocation.
12041204
unsafe { &mut this.ptr.as_mut().value }
12051205
}
1206+
1207+
/// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
1208+
/// clone.
1209+
///
1210+
/// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
1211+
/// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
1212+
///
1213+
/// # Examples
1214+
///
1215+
/// ```
1216+
/// #![feature(arc_unwrap_or_clone)]
1217+
/// # use std::{ptr, rc::Rc};
1218+
/// let inner = String::from("test");
1219+
/// let ptr = inner.as_ptr();
1220+
///
1221+
/// let rc = Rc::new(inner);
1222+
/// let inner = Rc::unwrap_or_clone(rc);
1223+
/// // The inner value was not cloned
1224+
/// assert!(ptr::eq(ptr, inner.as_ptr()));
1225+
///
1226+
/// let rc = Rc::new(inner);
1227+
/// let rc2 = rc.clone();
1228+
/// let inner = Rc::unwrap_or_clone(rc);
1229+
/// // Because there were 2 references, we had to clone the inner value.
1230+
/// assert!(!ptr::eq(ptr, inner.as_ptr()));
1231+
/// // `rc2` is the last reference, so when we unwrap it we get back
1232+
/// // the original `String`.
1233+
/// let inner = Rc::unwrap_or_clone(rc2);
1234+
/// assert!(ptr::eq(ptr, inner.as_ptr()));
1235+
/// ```
1236+
#[inline]
1237+
#[unstable(feature = "arc_unwrap_or_clone", issue = "93610")]
1238+
pub fn unwrap_or_clone(this: Self) -> T {
1239+
Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
1240+
}
12061241
}
12071242

12081243
impl Rc<dyn Any> {

library/alloc/src/sync.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1508,7 +1508,7 @@ impl<T: Clone> Arc<T> {
15081508
/// assert!(ptr::eq(ptr, inner.as_ptr()));
15091509
/// ```
15101510
#[inline]
1511-
#[unstable(feature = "arc_unwrap_or_clone", issue = "none")]
1511+
#[unstable(feature = "arc_unwrap_or_clone", issue = "93610")]
15121512
pub fn unwrap_or_clone(this: Self) -> T {
15131513
Arc::try_unwrap(this).unwrap_or_else(|arc| (*arc).clone())
15141514
}

0 commit comments

Comments
 (0)