Rollup merge of #95947 - cuviper:default-box, r=dtolnay

`impl const Default for Box<[T]>` and `Box<str>`

The unstable `const_default_impls` (#87864) already include empty `Vec<T>` and `String`. Now we extend that concept to `Box<[T]>` and `Box<str>` as well.

This obviates a hack in `rustc_ast`'s `P::<[T]>::new`.
This commit is contained in:
fee1-dead 2022-04-12 22:44:45 +10:00 committed by GitHub
commit 1d76dd9ee7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 21 additions and 12 deletions

View File

@ -9,6 +9,8 @@
test(attr(deny(warnings)))
)]
#![feature(box_patterns)]
#![feature(const_default_impls)]
#![feature(const_trait_impl)]
#![feature(crate_visibility_modifier)]
#![feature(if_let_guard)]
#![feature(label_break_value)]

View File

@ -128,14 +128,7 @@ impl<S: Encoder, T: Encodable<S>> Encodable<S> for P<T> {
impl<T> P<[T]> {
pub const fn new() -> P<[T]> {
// HACK(eddyb) bypass the lack of a `const fn` to create an empty `Box<[T]>`
// (as trait methods, `default` in this case, can't be `const fn` yet).
P {
ptr: unsafe {
use std::ptr::NonNull;
std::mem::transmute(NonNull::<[T; 0]>::dangling() as NonNull<[T]>)
},
}
P { ptr: Box::default() }
}
#[inline(never)]

View File

@ -1192,17 +1192,25 @@ impl<T: Default> Default for Box<T> {
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
impl<T> const Default for Box<[T]> {
fn default() -> Self {
Box::<[T; 0]>::new([])
let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
Box(ptr, Global)
}
}
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "default_box_extra", since = "1.17.0")]
impl Default for Box<str> {
#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
impl const Default for Box<str> {
fn default() -> Self {
unsafe { from_boxed_utf8_unchecked(Default::default()) }
// SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
let ptr: Unique<str> = unsafe {
let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
Unique::new_unchecked(bytes.as_ptr() as *mut str)
};
Box(ptr, Global)
}
}

View File

@ -6,6 +6,9 @@ pub const MY_VEC2: Vec<usize> = Default::default();
pub const MY_STRING: String = String::new();
pub const MY_STRING2: String = Default::default();
pub const MY_BOXED_SLICE: Box<[usize]> = Default::default();
pub const MY_BOXED_STR: Box<str> = Default::default();
use std::collections::{BTreeMap, BTreeSet};
pub const MY_BTREEMAP: BTreeMap<usize, usize> = BTreeMap::new();
@ -23,6 +26,9 @@ fn test_const() {
assert_eq!(MY_VEC, MY_VEC2);
assert_eq!(MY_STRING, MY_STRING2);
assert_eq!(MY_VEC, *MY_BOXED_SLICE);
assert_eq!(MY_STRING, *MY_BOXED_STR);
assert_eq!(MAP_LEN, 0);
assert_eq!(SET_LEN, 0);
assert!(MAP_IS_EMPTY && SET_IS_EMPTY);