mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-22 23:04:33 +00:00
impl const Default for Box<[T]> and Box<str>
This commit is contained in:
parent
625e4dd13a
commit
a2902ebe57
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user