@@ -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
12081243impl Rc < dyn Any > {
0 commit comments