Skip to content

Mapping and collecting an owned Vec to an item with the same size should reuse its allocation #75087

Closed
@jhpratt

Description

@jhpratt
#[repr(i8)]
pub enum Foo {
    A,
    B,
    C,
}

pub fn convert(vec: Vec<Foo>) -> Vec<i8> {
    vec.into_iter().map(|foo| foo as i8).collect()
    // unsafe { std::mem::transmute(vec) }
}

As it stands currently (on both stable and nightly), a new Vec is created in memory. As the source and target types are the same size in memory, I see no reason the compiler couldn't just map the value in-place, returning the same allocated ref (but with different semantics).

The commented out line is to indicate what I think should be the case for a trivial case where memory representations are identical. Obviously it wouldn't be quite as simple for most cases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions