Skip to content

Commit caf2c06

Browse files
authoredJan 31, 2021
Rollup merge of #80945 - sdroege:downcast-send-sync, r=m-ou-se
Add Box::downcast() for dyn Any + Send + Sync Looks like a plain omission, but unfortunately I just needed that in my code :)
2 parents 1e99f26 + 12014d2 commit caf2c06

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
 

‎library/alloc/src/boxed.rs

+33
Original file line numberDiff line numberDiff line change
@@ -1372,6 +1372,39 @@ impl<A: Allocator> Box<dyn Any + Send, A> {
13721372
}
13731373
}
13741374

1375+
impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1376+
#[inline]
1377+
#[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1378+
/// Attempt to downcast the box to a concrete type.
1379+
///
1380+
/// # Examples
1381+
///
1382+
/// ```
1383+
/// use std::any::Any;
1384+
///
1385+
/// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1386+
/// if let Ok(string) = value.downcast::<String>() {
1387+
/// println!("String ({}): {}", string.len(), string);
1388+
/// }
1389+
/// }
1390+
///
1391+
/// let my_string = "Hello World".to_string();
1392+
/// print_if_string(Box::new(my_string));
1393+
/// print_if_string(Box::new(0i8));
1394+
/// ```
1395+
pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1396+
if self.is::<T>() {
1397+
unsafe {
1398+
let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1399+
Box::into_raw_with_allocator(self);
1400+
Ok(Box::from_raw_in(raw as *mut T, alloc))
1401+
}
1402+
} else {
1403+
Err(self)
1404+
}
1405+
}
1406+
}
1407+
13751408
#[stable(feature = "rust1", since = "1.0.0")]
13761409
impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
13771410
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {

0 commit comments

Comments
 (0)
Please sign in to comment.