File tree 1 file changed +14
-4
lines changed
1 file changed +14
-4
lines changed Original file line number Diff line number Diff line change @@ -141,6 +141,9 @@ impl<T> Box<T> {
141
141
/// ```
142
142
#[ unstable( feature = "new_uninit" , issue = "63291" ) ]
143
143
pub fn new_uninit ( ) -> Box < mem:: MaybeUninit < T > > {
144
+ if mem:: size_of :: < T > ( ) == 0 {
145
+ return Box ( NonNull :: dangling ( ) . into ( ) )
146
+ }
144
147
let layout = alloc:: Layout :: new :: < mem:: MaybeUninit < T > > ( ) ;
145
148
let ptr = unsafe {
146
149
Global . alloc ( layout)
@@ -181,10 +184,17 @@ impl<T> Box<[T]> {
181
184
/// ```
182
185
#[ unstable( feature = "new_uninit" , issue = "63291" ) ]
183
186
pub fn new_uninit_slice ( len : usize ) -> Box < [ mem:: MaybeUninit < T > ] > {
184
- let layout = alloc:: Layout :: array :: < mem:: MaybeUninit < T > > ( len) . unwrap ( ) ;
185
- let ptr = unsafe { alloc:: alloc ( layout) } ;
186
- let unique = Unique :: new ( ptr) . unwrap_or_else ( || alloc:: handle_alloc_error ( layout) ) ;
187
- let slice = unsafe { slice:: from_raw_parts_mut ( unique. cast ( ) . as_ptr ( ) , len) } ;
187
+ let ptr = if mem:: size_of :: < T > ( ) == 0 || len == 0 {
188
+ NonNull :: dangling ( )
189
+ } else {
190
+ let layout = alloc:: Layout :: array :: < mem:: MaybeUninit < T > > ( len) . unwrap ( ) ;
191
+ unsafe {
192
+ Global . alloc ( layout)
193
+ . unwrap_or_else ( |_| alloc:: handle_alloc_error ( layout) )
194
+ . cast ( )
195
+ }
196
+ } ;
197
+ let slice = unsafe { slice:: from_raw_parts_mut ( ptr. as_ptr ( ) , len) } ;
188
198
Box ( Unique :: from ( slice) )
189
199
}
190
200
}
You can’t perform that action at this time.
0 commit comments