Skip to content

liballoc: introduce String, Vec const-slicing#128399

Merged
bors merged 1 commit into
rust-lang:masterfrom
npry:master
Oct 7, 2024
Merged

liballoc: introduce String, Vec const-slicing#128399
bors merged 1 commit into
rust-lang:masterfrom
npry:master

Conversation

@npry

@npry npry commented Jul 30, 2024

Copy link
Copy Markdown
Contributor

This change const-qualifies many methods on Vec and String, notably as_slice, as_str, len. These changes are made behind the unstable feature flag const_vec_string_slice.

Motivation

This is to support simultaneous variance over ownership and constness. I have an enum type that may contain either String or &str, and I want to produce a &str from it in a possibly-const context.

enum StrOrString<'s> {
    Str(&'s str),
    String(String),
}

impl<'s> StrOrString<'s> {
    const fn as_str(&self) -> &str {
        match self {
             // In a const-context, I really only expect to see this variant, but I can't switch the implementation
             // in some mode like #[cfg(const)] -- there has to be a single body
             Self::Str(s) => s,

             // so this is a problem, since it's not `const`
             Self::String(s) => s.as_str(), 
        }
    }
}

Currently String and Vec don't support this, but can without functional changes. Similar logic applies for len, capacity, is_empty.

Changes

The essential thing enabling this change is that Unique::as_ptr is const. This lets us convert RawVec::ptr -> Vec::as_ptr -> Vec::as_slice -> String::as_str.

I had to move the Deref implementations into as_{str,slice} because Deref isn't #[const_trait], but I would expect this change to be invisible up to inlining. I moved the DerefMut implementations as well for uniformity.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants