about summary refs log tree commit diff
path: root/src/liballoc
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2018-06-01 01:09:25 +0000
committerbors <bors@rust-lang.org>2018-06-01 01:09:25 +0000
commitb7a9d4ea744c9a99952bc4576727b57c58c0e958 (patch)
treeeb6581b24d1cbb2e9e2bde8c4d9e3b0b403ee6c4 /src/liballoc
parentefc508ba4ce9bc0ac3570436b3400c6e0b0f1dfb (diff)
parent87c3d7bee52fb99f922c77fa267729b7898bc9a6 (diff)
downloadrust-b7a9d4ea744c9a99952bc4576727b57c58c0e958.tar.gz
rust-b7a9d4ea744c9a99952bc4576727b57c58c0e958.zip
Auto merge of #50836 - jsgf:arc-downcast, r=SimonSapin
Arc downcast

Implement `downcast` for `Arc<Any + Send + Sync>` as part of #44608, and gated by the same `rc_downcast` feature.

This PR is mostly lightly-edited cut'n'paste.

This has two additional changes:
- The `downcast` implementation needs `Any + Send + Sync` implementations for `is` and `Debug`, and I added `downcast_ref` and `downcast_mut` for completeness/consistency. (Can these be insta-stabilized?)
- At @SimonSapin's suggestion, I converted `Arc` and `Rc` to use `NonNull::cast` to avoid an `unsafe` block in each which tidied things up nicely.
Diffstat (limited to 'src/liballoc')
-rw-r--r--src/liballoc/arc.rs59
-rw-r--r--src/liballoc/rc.rs12
2 files changed, 62 insertions, 9 deletions
diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs
index f7513248784..4026b3ababa 100644
--- a/src/liballoc/arc.rs
+++ b/src/liballoc/arc.rs
@@ -16,6 +16,7 @@
 //!
 //! [arc]: struct.Arc.html
 
+use core::any::Any;
 use core::sync::atomic;
 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
 use core::borrow;
@@ -971,6 +972,44 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
     }
 }
 
+impl Arc<Any + Send + Sync> {
+    #[inline]
+    #[unstable(feature = "rc_downcast", issue = "44608")]
+    /// Attempt to downcast the `Arc<Any + Send + Sync>` to a concrete type.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(rc_downcast)]
+    /// use std::any::Any;
+    /// use std::sync::Arc;
+    ///
+    /// fn print_if_string(value: Arc<Any + Send + Sync>) {
+    ///     if let Ok(string) = value.downcast::<String>() {
+    ///         println!("String ({}): {}", string.len(), string);
+    ///     }
+    /// }
+    ///
+    /// fn main() {
+    ///     let my_string = "Hello World".to_string();
+    ///     print_if_string(Arc::new(my_string));
+    ///     print_if_string(Arc::new(0i8));
+    /// }
+    /// ```
+    pub fn downcast<T>(self) -> Result<Arc<T>, Self>
+    where
+        T: Any + Send + Sync + 'static,
+    {
+        if (*self).is::<T>() {
+            let ptr = self.ptr.cast::<ArcInner<T>>();
+            mem::forget(self);
+            Ok(Arc { ptr, phantom: PhantomData })
+        } else {
+            Err(self)
+        }
+    }
+}
+
 impl<T> Weak<T> {
     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
     /// it. Calling [`upgrade`] on the return value always gives [`None`].
@@ -1844,6 +1883,26 @@ mod tests {
 
         assert_eq!(&r[..], [1, 2, 3]);
     }
+
+    #[test]
+    fn test_downcast() {
+        use std::any::Any;
+
+        let r1: Arc<Any + Send + Sync> = Arc::new(i32::max_value());
+        let r2: Arc<Any + Send + Sync> = Arc::new("abc");
+
+        assert!(r1.clone().downcast::<u32>().is_err());
+
+        let r1i32 = r1.downcast::<i32>();
+        assert!(r1i32.is_ok());
+        assert_eq!(r1i32.unwrap(), Arc::new(i32::max_value()));
+
+        assert!(r2.clone().downcast::<i32>().is_err());
+
+        let r2str = r2.downcast::<&'static str>();
+        assert!(r2str.is_ok());
+        assert_eq!(r2str.unwrap(), Arc::new("abc"));
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs
index 1648fc6b7ef..553c8b5ca32 100644
--- a/src/liballoc/rc.rs
+++ b/src/liballoc/rc.rs
@@ -644,15 +644,9 @@ impl Rc<Any> {
     /// ```
     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<Any>> {
         if (*self).is::<T>() {
-            // avoid the pointer arithmetic in from_raw
-            unsafe {
-                let raw: *const RcBox<Any> = self.ptr.as_ptr();
-                forget(self);
-                Ok(Rc {
-                    ptr: NonNull::new_unchecked(raw as *const RcBox<T> as *mut _),
-                    phantom: PhantomData,
-                })
-            }
+            let ptr = self.ptr.cast::<RcBox<T>>();
+            forget(self);
+            Ok(Rc { ptr, phantom: PhantomData })
         } else {
             Err(self)
         }