Skip to content

Commit 12014d2

Browse files
committed
Add Box::downcast() for dyn Any + Send + Sync
1 parent b6b4616 commit 12014d2

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
@@ -1364,6 +1364,39 @@ impl<A: Allocator> Box<dyn Any + Send, A> {
13641364
}
13651365
}
13661366

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

0 commit comments

Comments
 (0)