diff options
| author | bors <bors@rust-lang.org> | 2017-09-17 01:51:55 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2017-09-17 01:51:55 +0000 |
| commit | 71e37674a1f1f876003c308429cc1ef4d15edf87 (patch) | |
| tree | aa0010f1e01317cbc540f2e38c0b6371c09fce3c /src/liballoc | |
| parent | b492405b1fcfb8243481582182a0232fb5177021 (diff) | |
| parent | 2bd4dcf891d9cfe567c607fa8607f46b212b1aa3 (diff) | |
| download | rust-71e37674a1f1f876003c308429cc1ef4d15edf87.tar.gz rust-71e37674a1f1f876003c308429cc1ef4d15edf87.zip | |
Auto merge of #44634 - alexcrichton:rollup, r=alexcrichton
Rollup of 19 pull requests - Successful merges: #44273, #44356, #44395, #44531, #44537, #44542, #44560, #44567, #44574, #44577, #44586, #44589, #44590, #44593, #44598, #44606, #44609, #44616, #44631 - Failed merges:
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/rc.rs | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 47f537caf31..58c589697f4 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -244,6 +244,7 @@ use boxed::Box; #[cfg(test)] use std::boxed::Box; +use core::any::Any; use core::borrow; use core::cell::Cell; use core::cmp::Ordering; @@ -608,6 +609,46 @@ impl<T: Clone> Rc<T> { } } +impl Rc<Any> { + #[inline] + #[unstable(feature = "rc_downcast", issue = "44608")] + /// Attempt to downcast the `Rc<Any>` to a concrete type. + /// + /// # Examples + /// + /// ``` + /// #![feature(rc_downcast)] + /// use std::any::Any; + /// use std::rc::Rc; + /// + /// fn print_if_string(value: Rc<Any>) { + /// if let Ok(string) = value.downcast::<String>() { + /// println!("String ({}): {}", string.len(), string); + /// } + /// } + /// + /// fn main() { + /// let my_string = "Hello World".to_string(); + /// print_if_string(Rc::new(my_string)); + /// print_if_string(Rc::new(0i8)); + /// } + /// ``` + 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: Shared::new_unchecked(raw as *const RcBox<T> as *mut _), + }) + } + } else { + Err(self) + } + } +} + impl<T: ?Sized> Rc<T> { // Allocates an `RcBox<T>` with sufficient space for an unsized value unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> { @@ -1696,6 +1737,26 @@ mod tests { assert_eq!(&r[..], [1, 2, 3]); } + + #[test] + fn test_downcast() { + use std::any::Any; + + let r1: Rc<Any> = Rc::new(i32::max_value()); + let r2: Rc<Any> = Rc::new("abc"); + + assert!(r1.clone().downcast::<u32>().is_err()); + + let r1i32 = r1.downcast::<i32>(); + assert!(r1i32.is_ok()); + assert_eq!(r1i32.unwrap(), Rc::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(), Rc::new("abc")); + } } #[stable(feature = "rust1", since = "1.0.0")] |
