From f722964d00f9276b86777fab8db3fbfecd440ae7 Mon Sep 17 00:00:00 2001 From: Peter Todd Date: Tue, 28 Jan 2020 20:53:45 -0500 Subject: [PATCH] Minor: note why we can rely on Any trait for safety --- src/libcore/any.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/libcore/any.rs b/src/libcore/any.rs index af02e84d3fa53..97ef513cbcc63 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -194,7 +194,9 @@ impl dyn Any { #[inline] pub fn downcast_ref(&self) -> Option<&T> { if self.is::() { - // 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 @@ -228,7 +230,9 @@ impl dyn Any { #[inline] pub fn downcast_mut(&mut self) -> Option<&mut T> { if self.is::() { - // 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