mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-22 23:04:33 +00:00
dd4f062b07
liballoc: introduce String, Vec const-slicing 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. ```rust 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. |
||
---|---|---|
.. | ||
assembly | ||
auxiliary | ||
codegen | ||
codegen-units | ||
coverage | ||
coverage-run-rustdoc | ||
crashes | ||
debuginfo | ||
incremental | ||
mir-opt | ||
pretty | ||
run-make | ||
run-pass-valgrind | ||
rustdoc | ||
rustdoc-gui | ||
rustdoc-js | ||
rustdoc-js-std | ||
rustdoc-json | ||
rustdoc-ui | ||
ui | ||
ui-fulldeps | ||
COMPILER_TESTS.md |