@@ -1477,6 +1477,41 @@ impl<T: Clone> Arc<T> {
1477
1477
// either unique to begin with, or became one upon cloning the contents.
1478
1478
unsafe { Self :: get_mut_unchecked ( this) }
1479
1479
}
1480
+
1481
+ /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
1482
+ /// clone.
1483
+ ///
1484
+ /// Assuming `arc_t` is of type `Arc<T>`, this function is functionally equivalent to
1485
+ /// `(*arc_t).clone()`, but will avoid cloning the inner value where possible.
1486
+ ///
1487
+ /// # Examples
1488
+ ///
1489
+ /// ```
1490
+ /// #![feature(arc_unwrap_or_clone)]
1491
+ /// # use std::{ptr, sync::Arc};
1492
+ /// let inner = String::from("test");
1493
+ /// let ptr = inner.as_ptr();
1494
+ ///
1495
+ /// let arc = Arc::new(inner);
1496
+ /// let inner = Arc::unwrap_or_clone(arc);
1497
+ /// // The inner value was not cloned
1498
+ /// assert!(ptr::eq(ptr, inner.as_ptr()));
1499
+ ///
1500
+ /// let arc = Arc::new(inner);
1501
+ /// let arc2 = arc.clone();
1502
+ /// let inner = Arc::unwrap_or_clone(arc);
1503
+ /// // Because there were 2 references, we had to clone the inner value.
1504
+ /// assert!(!ptr::eq(ptr, inner.as_ptr()));
1505
+ /// // `arc2` is the last reference, so when we unwrap it we get back
1506
+ /// // the original `String`.
1507
+ /// let inner = Arc::unwrap_or_clone(arc2);
1508
+ /// assert!(ptr::eq(ptr, inner.as_ptr()));
1509
+ /// ```
1510
+ #[ inline]
1511
+ #[ unstable( feature = "arc_unwrap_or_clone" , issue = "none" ) ]
1512
+ pub fn unwrap_or_clone ( this : Self ) -> T {
1513
+ Arc :: try_unwrap ( this) . unwrap_or_else ( |arc| ( * arc) . clone ( ) )
1514
+ }
1480
1515
}
1481
1516
1482
1517
impl < T : ?Sized > Arc < T > {
0 commit comments