rust - How is from_raw_parts_mut able to transmute between types of different sizes? -
i looking @ code of from_raw_parts_mut
:
pub unsafe fn from_raw_parts_mut<'a, t>(p: *mut t, len: usize) -> &'a mut [t] { mem::transmute(repr { data: p, len: len }) }
it uses transmute
reinterpret repr
&mut [t]
. far understand, repr
128 bit struct. how transmute of differently sized types work?
mem::transmute()
work when transmuting type of same size - means &mut[t]
slice same size.
looking @ repr
:
#[repr(c)] struct repr<t> { pub data: *const t, pub len: usize, }
it has pointer data , length. slice - pointer array of items (which might actual array, or owned vec<t>
, etc.) length how many items valid.
the object passed around slice (under covers) repr
looks like, though data refers can 0 many t
fit memory.
in rust, references not implemented pointer in other languages. types "fat pointers". might not obvious @ first since, if familiar references/pointers in other languages! examples are:
- slices
&[t]
,&mut [t]
, described above, pointer , length. length needed bounds checks. example, can pass slice corresponding part of array orvec
function. - trait objects
&trait
orbox<trait>
,trait
trait rather concrete type, pointer concrete type , pointer vtable — information needed call trait methods on object, given concrete type not known.
Comments
Post a Comment