Skip to content
Myr

Change Error::construct to unsafe fn because TypeId must be correct

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent eaa819d · Browse files · 1 file+30 added−17 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+30 added−17 removed

  • other:+30 added−17 removed

1 file+30 added−17 removed

modified:src/error.rs+30 added-17 removed
31 unmodified lines
32 pub fn new<E>(error: E) -> Self33 where34 E: StdError + Send + Sync + 'static,35 {36 let type_id = TypeId::of::<E>();37 let backtrace = backtrace_if_absent!(error);3839 // Safety: passing typeid of the right type E.40 unsafe {37 Error::construct(error, TypeId::of::<E>(), backtrace)41 Error::construct(error, type_id, backtrace)42 }43 }4445 pub(crate) fn new_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self46 where47 M: Display + Debug + Send + Sync + 'static,48 {44 Error::construct(MessageError(message), TypeId::of::<M>(), backtrace)49 let error = MessageError(message);50 let type_id = TypeId::of::<M>();5152 // Safety: MessageError is repr(transparent) so MessageError<M> has the53 // same layout as the typeid specifies.54 unsafe {55 Error::construct(error, type_id, backtrace)56 }57 }5859 // Takes backtrace as argument rather than capturing it here so that the60 // user sees one fewer layer of wrapping noise in the backtrace.61 //62 // Unsafe because the type represented by type_id must have the same layout63 // as E or else we allow invalid downcasts.49 fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> Self64 unsafe fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> Self65 where66 E: StdError + Send + Sync + 'static,67 {53 unsafe {54 let vtable = &ErrorVTable {55 object: object_raw::<E>,56 object_mut: object_mut_raw::<E>,57 };58 let inner = Box::new(ErrorImpl {59 vtable,60 type_id,61 backtrace,62 error,63 });64 Error {65 inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),68 let vtable = &ErrorVTable {69 object: object_raw::<E>,70 object_mut: object_mut_raw::<E>,71 };72 let inner = Box::new(ErrorImpl {73 vtable,74 type_id,75 backtrace,76 error,77 });78 Error {79 inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),66 }80 }81 }8283 /// Wrap the error value with additional context.
433 unmodified lines