Skip to content

Commit

Permalink
Minor: note why we can rely on Any trait for safety
Browse files Browse the repository at this point in the history
  • Loading branch information
petertodd committed Jan 29, 2020
1 parent 3761dcd commit f722964
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/libcore/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ impl dyn Any {
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
// SAFETY: just checked whether we are pointing to the correct type
// SAFETY: just checked whether we are pointing to the correct type, and we can rely on
// that check for memory safety because we have implemented Any for all types; no other
// impls can exist as they would conflict with our impl.
unsafe { Some(&*(self as *const dyn Any as *const T)) }
} else {
None
Expand Down Expand Up @@ -228,7 +230,9 @@ impl dyn Any {
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
// SAFETY: just checked whether we are pointing to the correct type
// SAFETY: just checked whether we are pointing to the correct type, and we can rely on
// that check for memory safety because we have implemented Any for all types; no other
// impls can exist as they would conflict with our impl.
unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) }
} else {
None
Expand Down

0 comments on commit f722964

Please sign in to comment.