Skip to content

str::from_raw_parts #167

Closed
Closed
@Kixiron

Description

@Kixiron

Proposal

Add the str::from_raw_parts and str::from_raw_parts_mut apis

mod str {
    pub const unsafe fn from_raw_parts<'a>(data: *const u8, len: usize) -> &'a str { ... }
    
    pub unsafe fn from_raw_parts_mut<'a>(data: *mut u8, len: usize) -> &'a mut str { ... }
}

Problem statement

Creating a str from raw parts is a fairly boilerplate filled task.

Motivation, use-cases

Often in unsafe or FFI-related code users end up creating strings from their constituent parts, pointers and lengths. However, as of now there's no direct way to do this for str, instead the user must first create a byte slice and then create a string slice from said byte slice, requiring the user to write more code than they really should have to. This proposal turns the pattern of

let bytes = slice::from_raw_parts(ptr, len);
str::from_utf8_unchecked(bytes)

into a simple str::from_raw_parts(ptr, len) call.

Solution sketches

Instead of putting the functions within the str module, they could be methods on str itself to keep the user from having to import the str module or fully qualifying core::str::from_raw_parts wherever they need to use the function.

Links and related work

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions