@@ -146,9 +146,7 @@ impl<'a> MemoryMap for MemoryMapRefMut<'a> {
146146
147147impl < ' a > MemoryMapMut for MemoryMapRefMut < ' a > {
148148 fn sort ( & mut self ) {
149- unsafe {
150- self . qsort ( 0 , self . len - 1 ) ;
151- }
149+ self . qsort ( 0 , self . len - 1 ) ;
152150 }
153151
154152 unsafe fn buffer_mut ( & mut self ) -> & mut [ u8 ] {
@@ -159,7 +157,7 @@ impl<'a> MemoryMapMut for MemoryMapRefMut<'a> {
159157impl < ' a > MemoryMapRefMut < ' a > {
160158 /// Hoare partition scheme for quicksort.
161159 /// Must be called with `low` and `high` being indices within bounds.
162- unsafe fn qsort ( & mut self , low : usize , high : usize ) {
160+ fn qsort ( & mut self , low : usize , high : usize ) {
163161 if low >= high {
164162 return ;
165163 }
@@ -169,7 +167,7 @@ impl<'a> MemoryMapRefMut<'a> {
169167 self . qsort ( p + 1 , high) ;
170168 }
171169
172- unsafe fn partition ( & mut self , low : usize , high : usize ) -> usize {
170+ fn partition ( & mut self , low : usize , high : usize ) -> usize {
173171 let pivot = self . get_element_phys_addr ( low + ( high - low) / 2 ) ;
174172
175173 let mut left_index = low. wrapping_sub ( 1 ) ;
@@ -197,24 +195,30 @@ impl<'a> MemoryMapRefMut<'a> {
197195 }
198196
199197 /// Indices must be smaller than len.
200- unsafe fn swap ( & mut self , index1 : usize , index2 : usize ) {
198+ fn swap ( & mut self , index1 : usize , index2 : usize ) {
199+ assert ! ( index1 < self . len) ;
200+ assert ! ( index2 < self . len) ;
201+
201202 if index1 == index2 {
202203 return ;
203204 }
204205
205206 let base = self . buf . as_mut_ptr ( ) ;
206207
208+ let offset1 = index1 * self . meta . desc_size ;
209+ let offset2 = index2 * self . meta . desc_size ;
210+
211+ // SAFETY: the data starting at `offset1` and `offset2` are valid
212+ // descriptors, and do not overlap.
207213 unsafe {
208- ptr:: swap_nonoverlapping (
209- base. add ( index1 * self . meta . desc_size ) ,
210- base. add ( index2 * self . meta . desc_size ) ,
211- self . meta . desc_size ,
212- ) ;
214+ ptr:: swap_nonoverlapping ( base. add ( offset1) , base. add ( offset2) , self . meta . desc_size ) ;
213215 }
214216 }
215217
216218 fn get_element_phys_addr ( & self , index : usize ) -> PhysicalAddress {
219+ assert ! ( index < self . len) ;
217220 let offset = index. checked_mul ( self . meta . desc_size ) . unwrap ( ) ;
221+ // SAFETY: the data starting at `offset` is a valid descriptor.
218222 let elem = unsafe { & * self . buf . as_ptr ( ) . add ( offset) . cast :: < MemoryDescriptor > ( ) } ;
219223 elem. phys_start
220224 }
0 commit comments