Use pointer casts instead of tramsutes to raw::TraitObject

Casting `*const T` to `*const U` with `U: Sized` is allowed even if `T: ?Sized`.
This safely extracts the data pointer out of a trait object,
without relying on the memory representation of trait objects.
This commit is contained in:
Simon Sapin 2017-10-13 21:55:11 +02:00
parent 78aaa85aec
commit e7c53d4ca2
3 changed files with 10 additions and 52 deletions

View file

@ -44,7 +44,7 @@ use multicol::MulticolFlow;
use parallel::FlowParallelInfo;
use serde::ser::{Serialize, SerializeStruct, Serializer};
use servo_geometry::{au_rect_to_f32_rect, f32_rect_to_au_rect, max_rect};
use std::{fmt, mem};
use std::fmt;
use std::iter::Zip;
use std::slice::IterMut;
use std::sync::Arc;
@ -452,10 +452,9 @@ pub trait Flow: fmt::Debug + Sync + Send + 'static {
#[inline(always)]
#[allow(unsafe_code)]
pub fn base<T: ?Sized + Flow>(this: &T) -> &BaseFlow {
unsafe {
let obj = mem::transmute::<&&T, &::TraitObject>(&this);
mem::transmute::<*mut (), &BaseFlow>(obj.data)
}
let ptr: *const T = this;
let ptr = ptr as *const BaseFlow;
unsafe { &*ptr }
}
/// Iterates over the children of this immutable flow.
@ -466,10 +465,9 @@ pub fn child_iter<'a>(flow: &'a Flow) -> FlowListIterator {
#[inline(always)]
#[allow(unsafe_code)]
pub fn mut_base<T: ?Sized + Flow>(this: &mut T) -> &mut BaseFlow {
unsafe {
let obj = mem::transmute::<&&mut T, &::TraitObject>(&this);
mem::transmute::<*mut (), &mut BaseFlow>(obj.data)
}
let ptr: *mut T = this;
let ptr = ptr as *mut BaseFlow;
unsafe { &mut *ptr }
}
/// Iterates over the children of this flow.
@ -1419,11 +1417,9 @@ impl ContainingBlockLink {
pub struct OpaqueFlow(pub usize);
impl OpaqueFlow {
#[allow(unsafe_code)]
pub fn from_flow(flow: &Flow) -> OpaqueFlow {
unsafe {
let object = mem::transmute::<&Flow, ::TraitObject>(flow);
OpaqueFlow(object.data as usize)
}
let object_ptr: *const Flow = flow;
let data_ptr = object_ptr as *const ();
OpaqueFlow(data_ptr as usize)
}
}