Skip to content
Myr

Deallocate with the right Layout during downcast

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 8895b00 · Browse files · 1 file+16 added−4 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+16 added−4 removed

  • other:+16 added−4 removed

1 file+16 added−4 removed

modified:src/error.rs+16 added-4 removed
80 unmodified lines
81 E: StdError + Send + Sync + 'static,82 {83 let vtable = &ErrorVTable {84 object_drop: object_drop::<E>,85 object_drop_front: object_drop_front::<E>,86 object_raw: object_raw::<E>,87 object_mut_raw: object_mut_raw::<E>,88 };89 let inner = Box::new(ErrorImpl {
147 unmodified lines
237 pub fn downcast<E>(self) -> Result<E, Self>238 where239 E: Display + Debug + Send + Sync + 'static,240 {240 if let Some(error) = self.downcast_ref::<E>() {241 if self.is::<E>() {242 let outer = ManuallyDrop::new(self);243 unsafe {242 let error = ptr::read(error);243 drop(ptr::read(&self.inner));244 mem::forget(self);244 let error = ptr::read(&outer.inner.error as *const () as *const E);245 let inner = ptr::read(&outer.inner);246 let erased = ManuallyDrop::into_inner(inner);247 (erased.vtable.object_drop_front)(erased);248 Ok(error)249 }250 } else {251 Err(self)
143 unmodified lines
395}396397struct ErrorVTable {398 object_drop: unsafe fn(Box<ErrorImpl<()>>),399 object_drop_front: unsafe fn(Box<ErrorImpl<()>>),400 object_raw: fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),401 object_mut_raw: fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),402}403
3 unmodified lines
407 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);408 drop(unerased);409}410411unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {412 // Drop the fields of ErrorImpl other than E as well as the Box allocation,413 // without dropping E itself. This is used by downcast after doing a414 // ptr::read to take ownership of the E.415 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);416 drop(unerased);417}418419fn object_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)420where421 E: StdError + Send + Sync + 'static,422{
159 unmodified lines