182
182
//! [valid]: ptr#safety
183
183
184
184
#![ stable( feature = "rust1" , since = "1.0.0" ) ]
185
+ #![ feature( ub_checks) ]
185
186
186
187
use core:: borrow:: { Borrow , BorrowMut } ;
187
188
#[ cfg( not( no_global_oom_handling) ) ]
@@ -200,6 +201,7 @@ use core::ops::{
200
201
use core:: pin:: { Pin , PinCoerceUnsized } ;
201
202
use core:: ptr:: { self , NonNull , Unique } ;
202
203
use core:: task:: { Context , Poll } ;
204
+ use core:: ub_checks:: assert_pointer_is_aligned_and_not_null;
203
205
204
206
#[ cfg( not( no_global_oom_handling) ) ]
205
207
use crate :: alloc:: handle_alloc_error;
@@ -1017,7 +1019,7 @@ impl<T: ?Sized> Box<T> {
1017
1019
/// resulting `Box`. Specifically, the `Box` destructor will call
1018
1020
/// the destructor of `T` and free the allocated memory. For this
1019
1021
/// to be safe, the memory must have been allocated in accordance
1020
- /// with the [memory layout] used by `Box` .
1022
+ /// with the [memory layout] used by `Box`.
1021
1023
///
1022
1024
/// # Safety
1023
1025
///
@@ -1056,8 +1058,9 @@ impl<T: ?Sized> Box<T> {
1056
1058
#[ stable( feature = "box_raw" , since = "1.4.0" ) ]
1057
1059
#[ inline]
1058
1060
#[ must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`" ]
1059
- pub unsafe fn from_raw ( raw : * mut T ) -> Self {
1060
- unsafe { Self :: from_raw_in ( raw, Global ) }
1061
+ pub unsafe fn from_raw ( ptr : * mut T ) -> Self {
1062
+ assert_pointer_is_aligned_and_not_null ! ( "Box::from_raw" , ptr, align_of:: <T >( ) , T :: IS_ZST ) ;
1063
+ unsafe { Self :: from_raw_in ( ptr, Global ) }
1061
1064
}
1062
1065
1063
1066
/// Constructs a box from a `NonNull` pointer.
@@ -1111,6 +1114,12 @@ impl<T: ?Sized> Box<T> {
1111
1114
#[ inline]
1112
1115
#[ must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`" ]
1113
1116
pub unsafe fn from_non_null ( ptr : NonNull < T > ) -> Self {
1117
+ assert_pointer_is_aligned_and_not_null ! (
1118
+ "Box::from_non_null" ,
1119
+ ptr,
1120
+ align_of:: <T >( ) ,
1121
+ T :: IS_ZST
1122
+ ) ;
1114
1123
unsafe { Self :: from_raw ( ptr. as_ptr ( ) ) }
1115
1124
}
1116
1125
}
@@ -1166,8 +1175,14 @@ impl<T: ?Sized, A: Allocator> Box<T, A> {
1166
1175
#[ unstable( feature = "allocator_api" , issue = "32838" ) ]
1167
1176
#[ rustc_const_unstable( feature = "const_box" , issue = "92521" ) ]
1168
1177
#[ inline]
1169
- pub const unsafe fn from_raw_in ( raw : * mut T , alloc : A ) -> Self {
1170
- Box ( unsafe { Unique :: new_unchecked ( raw) } , alloc)
1178
+ pub const unsafe fn from_raw_in ( ptr : * mut T , alloc : A ) -> Self {
1179
+ assert_pointer_is_aligned_and_not_null ! (
1180
+ "Box::from_raw_in" ,
1181
+ ptr,
1182
+ align_of:: <T >( ) ,
1183
+ T :: IS_ZST
1184
+ ) ;
1185
+ Box ( unsafe { Unique :: new_unchecked ( ptr) } , alloc)
1171
1186
}
1172
1187
1173
1188
/// Constructs a box from a `NonNull` pointer in the given allocator.
0 commit comments