@@ -1203,6 +1203,41 @@ impl<T: Clone> Rc<T> {
1203
1203
// reference to the allocation.
1204
1204
unsafe { & mut this. ptr . as_mut ( ) . value }
1205
1205
}
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
+ }
1206
1241
}
1207
1242
1208
1243
impl Rc < dyn Any > {
0 commit comments