Skip to content

Commit cda81da

Browse files
committed
avoid unsafe code, use upcasting-trait instead (trick by oli)
1 parent 82f4a1a commit cda81da

File tree

1 file changed

+16
-25
lines changed

1 file changed

+16
-25
lines changed

src/librustc/mir/interpret/error.rs

+16-25
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ use rustc_hir as hir;
1414
use rustc_macros::HashStable;
1515
use rustc_session::CtfeBacktrace;
1616
use rustc_span::{def_id::DefId, Pos, Span};
17-
use std::{
18-
any::{Any, TypeId},
19-
fmt, mem,
20-
};
17+
use std::{any::Any, fmt, mem};
2118

2219
#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable)]
2320
pub enum ErrorHandled {
@@ -513,32 +510,26 @@ impl fmt::Debug for ResourceExhaustionInfo {
513510
}
514511
}
515512

513+
/// A trait to work around not having trait object upcasting.
514+
pub trait AsAny: Any {
515+
fn as_any(&self) -> &dyn Any;
516+
}
517+
518+
impl<T: Any> AsAny for T {
519+
#[inline(always)]
520+
fn as_any(&self) -> &dyn Any {
521+
self
522+
}
523+
}
524+
516525
/// A trait for machine-specific errors (or other "machine stop" conditions).
517-
pub trait MachineStopType: Any + fmt::Debug + Send {}
526+
pub trait MachineStopType: AsAny + fmt::Debug + Send {}
518527
impl MachineStopType for String {}
519528

520-
// Copy-pasted from `any.rs`; there does not seem to be a way to re-use that.
521529
impl dyn MachineStopType {
522-
pub fn is<T: Any>(&self) -> bool {
523-
// Get `TypeId` of the type this function is instantiated with.
524-
let t = TypeId::of::<T>();
525-
526-
// Get `TypeId` of the type in the trait object (`self`).
527-
let concrete = self.type_id();
528-
529-
// Compare both `TypeId`s on equality.
530-
t == concrete
531-
}
532-
530+
#[inline(always)]
533531
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
534-
if self.is::<T>() {
535-
// SAFETY: just checked whether we are pointing to the correct type, and we can rely on
536-
// that check for memory safety because `Any` is implemented for all types; no other
537-
// impls can exist as they would conflict with our impl.
538-
unsafe { Some(&*(self as *const dyn MachineStopType as *const T)) }
539-
} else {
540-
None
541-
}
532+
self.as_any().downcast_ref()
542533
}
543534
}
544535

0 commit comments

Comments
 (0)