From 37f5cf563c2c039503e8e50e252f2c1b31d69268 Mon Sep 17 00:00:00 2001 From: Jeremy Fitzhardinge Date: Thu, 17 May 2018 08:17:35 -0700 Subject: [PATCH] Implement `downcast` for `Arc` We only need to implement it for `Any + Send + Sync` because in practice that's the only useful combination for `Arc` and `Any`. Implementation for #44608 under the `rc_downcast` feature. --- src/liballoc/arc.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index f75132487849f..0795498f87f9d 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,49 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc { } } +impl Arc { + #[inline] + #[unstable(feature = "rc_downcast", issue = "44608")] + /// Attempt to downcast the `Arc` to a concrete type. + /// + /// # Examples + /// + /// ``` + /// #![feature(rc_downcast)] + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// fn print_if_string(value: Arc) { + /// if let Ok(string) = value.downcast::() { + /// 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(self) -> Result, Self> + where + T: Any + Send + Sync + 'static, + { + if (*self).is::() { + unsafe { + let raw: *const ArcInner = self.ptr.as_ptr(); + mem::forget(self); + Ok(Arc { + ptr: NonNull::new_unchecked(raw as *const ArcInner as *mut _), + phantom: PhantomData, + }) + } + } else { + Err(self) + } + } +} + impl Weak { /// Constructs a new `Weak`, allocating memory for `T` without initializing /// it. Calling [`upgrade`] on the return value always gives [`None`]. @@ -1844,6 +1888,26 @@ mod tests { assert_eq!(&r[..], [1, 2, 3]); } + + #[test] + fn test_downcast() { + use std::any::Any; + + let r1: Arc = Arc::new(i32::max_value()); + let r2: Arc = Arc::new("abc"); + + assert!(r1.clone().downcast::().is_err()); + + let r1i32 = r1.downcast::(); + assert!(r1i32.is_ok()); + assert_eq!(r1i32.unwrap(), Arc::new(i32::max_value())); + + assert!(r2.clone().downcast::().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")]