rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
99.18k stars 12.81k forks source link

Tracking Issue for `const_vec_string_slice` #129041

Open GrigorenkoPV opened 3 months ago

GrigorenkoPV commented 3 months ago

Feature gate: #![feature(const_vec_string_slice)]

This is a tracking issue for making a bunch of String and Vec methods const.

Public API

The following methods are now const:

impl String {
    pub const fn into_bytes(self) -> Vec<u8>
    pub const fn as_str(&self) -> &str
    pub const fn capacity(&self) -> usize
    pub const fn as_bytes(&self) -> &[u8]
    pub const fn len(&self) -> usize
    pub const fn is_empty(&self) -> bool
}

impl Vec<T> {
    pub const fn capacity(&self) -> usize
    pub const fn as_slice(&self) -> &[T]
    pub const fn as_ptr(&self) -> *const T
    pub const fn len(&self) -> usize
    pub const fn is_empty(&self) -> bool
}

Steps / History

Unresolved Questions

@rustbot label A-str

Esper89 commented 3 months ago

This would be very useful for const fns that sometimes need to handle runtime data too, such as a const fn method that needs to use a Cow<'static, [T]> field.

For example:

struct Foo(Cow<'static, [u32]>);

impl Foo {
    // Initialize with heap-allocated data at runtime.
    fn heap(data: Vec<u32>) -> Self {
        Foo(Cow::Owned(data))
    }

    // Initialize with static data at compile-time.
    const fn static(data: &'static [u32]) -> Self {
        Foo(Cow::Borrowed(data))
    }

    // Access the data, possibly at compile-time, possibly at runtime.
    const fn data(&self) -> &[u32] {
        match self.0 {
            Cow::Borrowed(slice) => slice,
            Cow::Owned(vec) => vec.as_slice(),
        }
    }
}
RalfJung commented 3 days ago

@rust-lang/libs-api from a const-eval perspective, these functions all look totally harmless. One can't actually construct non-trivial Vec/String in const, but according to the examples above it could still be useful to have these as const fn. So, I propose we move ahead with stabilizing these.

dtolnay commented 3 days ago

@rfcbot fcp merge

rfcbot commented 3 days ago

Team member @dtolnay has proposed to merge this. The next step is review by the rest of the tagged team members:

No concerns currently listed.

Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!

See this document for info about what commands tagged team members can give me.