Skip to content

Commit 7a46b59

Browse files
committed
Add initial downcast_trait impl
1 parent d40408e commit 7a46b59

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

library/core/src/any.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@
8686
8787
#![stable(feature = "rust1", since = "1.0.0")]
8888

89-
use crate::{fmt, hash, intrinsics};
89+
use crate::{fmt, hash, intrinsics, ptr};
9090

9191
///////////////////////////////////////////////////////////////////////////////
9292
// Any trait
@@ -896,3 +896,22 @@ pub const fn type_name<T: ?Sized>() -> &'static str {
896896
pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
897897
type_name::<T>()
898898
}
899+
900+
#[allow(missing_docs)]
901+
#[must_use]
902+
#[unstable(feature = "downcast_trait", issue = "69420")]
903+
pub const fn downcast_trait<
904+
T: Any + 'static,
905+
U: ptr::Pointee<Metadata = ptr::DynMetadata<U>> + ?Sized + 'static,
906+
>(
907+
t: &T,
908+
) -> Option<&U> {
909+
let vtable: Option<ptr::DynMetadata<U>> = const { intrinsics::vtable_for::<T, U>() };
910+
match vtable {
911+
Some(dyn_metadata) => {
912+
let pointer = ptr::from_raw_parts(t, dyn_metadata);
913+
Some(unsafe { &*pointer })
914+
}
915+
None => None,
916+
}
917+
}

0 commit comments

Comments
 (0)