44
55use alloc:: { alloc:: Layout , string:: String } ;
66use core:: {
7- mem:: forget,
7+ mem:: { align_of , forget} ,
88 ops:: { Deref , DerefMut } ,
99 ptr:: NonNull ,
1010} ;
@@ -22,7 +22,7 @@ pub(crate) struct BoxedString {
2222#[ cfg( endian = "big" ) ]
2323#[ repr( C ) ]
2424pub ( crate ) struct BoxedString {
25- length : usize ,
25+ len : usize ,
2626 cap : usize ,
2727 ptr : NunNull < u8 > ,
2828}
@@ -44,8 +44,17 @@ impl GenericString for BoxedString {
4444impl BoxedString {
4545 const MINIMAL_CAPACITY : usize = MAX_INLINE * 2 ;
4646
47+ pub ( crate ) fn check_alignment ( this : & Self ) -> usize {
48+ let ptr: * const u8 = this. ptr . as_ptr ( ) ;
49+ ptr. align_offset ( 2 )
50+ }
51+
4752 fn layout_for ( cap : usize ) -> Layout {
48- let layout = Layout :: array :: < u8 > ( cap) . unwrap ( ) ;
53+ // Always request memory that is specifically aligned to at least 2, so
54+ // the least significant bit is guaranteed to be 0.
55+ let layout = Layout :: array :: < u8 > ( cap)
56+ . and_then ( |layout| layout. align_to ( align_of :: < u16 > ( ) ) )
57+ . unwrap ( ) ;
4958 assert ! (
5059 layout. size( ) <= isize :: MAX as usize ,
5160 "allocation too large!"
@@ -56,11 +65,12 @@ impl BoxedString {
5665 fn alloc ( cap : usize ) -> NonNull < u8 > {
5766 let layout = Self :: layout_for ( cap) ;
5867 #[ allow( unsafe_code) ]
59- let ptr = unsafe { alloc:: alloc:: alloc ( layout) } ;
60- match NonNull :: new ( ptr) {
68+ let ptr = match NonNull :: new ( unsafe { alloc:: alloc:: alloc ( layout) } ) {
6169 Some ( ptr) => ptr,
6270 None => alloc:: alloc:: handle_alloc_error ( layout) ,
63- }
71+ } ;
72+ debug_assert ! ( ptr. as_ptr( ) . align_offset( 2 ) == 0 ) ;
73+ ptr
6474 }
6575
6676 fn realloc ( & mut self , cap : usize ) {
@@ -74,6 +84,7 @@ impl BoxedString {
7484 None => alloc:: alloc:: handle_alloc_error ( layout) ,
7585 } ;
7686 self . cap = cap;
87+ debug_assert ! ( self . ptr. as_ptr( ) . align_offset( 2 ) == 0 ) ;
7788 }
7889
7990 pub ( crate ) fn ensure_capacity ( & mut self , target_cap : usize ) {
0 commit comments