File tree 3 files changed +33
-3
lines changed
3 files changed +33
-3
lines changed Original file line number Diff line number Diff line change @@ -142,6 +142,9 @@ impl<T> Box<T> {
142
142
#[ unstable( feature = "new_uninit" , issue = "63291" ) ]
143
143
pub fn new_uninit ( ) -> Box < mem:: MaybeUninit < T > > {
144
144
let layout = alloc:: Layout :: new :: < mem:: MaybeUninit < T > > ( ) ;
145
+ if layout. size ( ) == 0 {
146
+ return Box ( NonNull :: dangling ( ) . into ( ) )
147
+ }
145
148
let ptr = unsafe {
146
149
Global . alloc ( layout)
147
150
. unwrap_or_else ( |_| alloc:: handle_alloc_error ( layout) )
@@ -182,9 +185,16 @@ impl<T> Box<[T]> {
182
185
#[ unstable( feature = "new_uninit" , issue = "63291" ) ]
183
186
pub fn new_uninit_slice ( len : usize ) -> Box < [ mem:: MaybeUninit < T > ] > {
184
187
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) } ;
188
+ let ptr = if layout. size ( ) == 0 {
189
+ NonNull :: dangling ( )
190
+ } else {
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
}
Original file line number Diff line number Diff line change
1
+ use std:: ptr:: NonNull ;
2
+ use std:: mem:: MaybeUninit ;
3
+
4
+ #[ test]
5
+ fn unitialized_zero_size_box ( ) {
6
+ assert_eq ! (
7
+ & * Box :: <( ) >:: new_uninit( ) as * const _,
8
+ NonNull :: <MaybeUninit <( ) >>:: dangling( ) . as_ptr( ) ,
9
+ ) ;
10
+ assert_eq ! (
11
+ Box :: <[ ( ) ] >:: new_uninit_slice( 4 ) . as_ptr( ) ,
12
+ NonNull :: <MaybeUninit <( ) >>:: dangling( ) . as_ptr( ) ,
13
+ ) ;
14
+ assert_eq ! (
15
+ Box :: <[ String ] >:: new_uninit_slice( 0 ) . as_ptr( ) ,
16
+ NonNull :: <MaybeUninit <String >>:: dangling( ) . as_ptr( ) ,
17
+ ) ;
18
+ }
Original file line number Diff line number Diff line change 2
2
#![ feature( box_syntax) ]
3
3
#![ feature( drain_filter) ]
4
4
#![ feature( exact_size_is_empty) ]
5
+ #![ feature( new_uninit) ]
5
6
#![ feature( option_flattening) ]
6
7
#![ feature( pattern) ]
7
8
#![ feature( trusted_len) ]
@@ -14,6 +15,7 @@ use std::collections::hash_map::DefaultHasher;
14
15
15
16
mod arc;
16
17
mod binary_heap;
18
+ mod boxed;
17
19
mod btree;
18
20
mod cow_str;
19
21
mod fmt;
You can’t perform that action at this time.
0 commit comments