Skip to content

#[repr(transparent)] for str and String #70473

Open
@RReverser

Description

@RReverser

Similarly to #52976, I'd suggest that str and String should have a guaranteed transparent representation of [u8] and Vec<u8> correspondingly.

They are a newtype wrappers of these types under the hood anyway, and I don't see any reasons why they would need to behave differently in the future, and making them different probably would become a breaking change anyway as it would break things like String::from_raw_parts constructed from raw parts of the Vec.

While String::from_raw_parts already covers most common cases, there are still other cases where it would be desired to have guaranteed representation.

One such example is constructing Rc<String> from a Rc<Vec<u8>> where a library might want to check UTF-8 validity before construction and then Rc::from_raw + Rc::into_raw one type into another without actually copying the data.

Currently this is not possible to do safely because it's not guaranteed that the *const Vec<u8> returned from the first into_raw is compatible with *const String accepted by the second.

While this particular case could be alleviated by adding a special method, there are lots of other containers where such compatibility between these types might be desirable, and I don't see any reasons why it couldn't be guaranteed at a lower level.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-reprArea: the `#[repr(stuff)]` attributeT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions