diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index fe48e2458cd16..d100ce14286b4 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -2933,16 +2933,32 @@ impl SliceIndex<[T]> for ops::RangeToInclusive { // Common traits //////////////////////////////////////////////////////////////////////////////// +// Slices could just use rvalue static promotion, but making them ourselves +// means we can skip the private const generation in LLVM and matches the +// behaviour of `Vec::::new()` and `Box::<[T]>::default()`. + #[stable(feature = "rust1", since = "1.0.0")] impl Default for &[T] { /// Creates an empty slice. - fn default() -> Self { &[] } + fn default() -> Self { + // SAFETY: using `dangling` for zero-length slices is mentioned + // explicitly in the safety documentation for `from_raw_parts`. + unsafe { + from_raw_parts(ptr::NonNull::dangling().as_ptr(), 0) + } + } } #[stable(feature = "mut_slice_default", since = "1.5.0")] impl Default for &mut [T] { /// Creates a mutable empty slice. - fn default() -> Self { &mut [] } + fn default() -> Self { + // SAFETY: using `dangling` for zero-length slices is mentioned + // explicitly in the safety documentation for `from_raw_parts`. + unsafe { + from_raw_parts_mut(ptr::NonNull::dangling().as_ptr(), 0) + } + } } //