Skip to content

Can the layouts of Vec<i32> and Vec<u32> guaranteed to be the same? #560

Closed
@davidzeng0

Description

@davidzeng0

Currently, the layouts of Vec<A> and Vec<B> have no guarantees. It would be useful in some cases to know the layout of Vec<A> for some A is the same as Vec<B>. For my usecase the exact field order doesn't matter, just that they could be the same as another type from within the same compilation.

Specifically, for any two types T and U, if their layout and alignment are the exact same, all bit patterns are valid for both, and are Freeze and Unpin, can &mut Vec<T> be transmuted to &mut Vec<U> and pushed to without immediate UB?

If such layout guarantees of Vec do not exist, can we expect them to exist at a later date?

Example

let mut v = vec![1i32];

let r: &mut Vec<u32> = unsafe { transmute(&mut v) };

r.push(2);

println!("{:?}", v);

I would also like to ask the question for Option, but Vec seems like it could achieve such a guarantee more easily because its data is behind a pointer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions