@@ -209,7 +209,6 @@ where
209
209
/// # Safety
210
210
///
211
211
/// - `count` must be less than or equal to `self.len`.
212
- #[ expect( unused) ]
213
212
unsafe fn dec_len ( & mut self , count : usize ) -> & mut [ T ] {
214
213
debug_assert ! ( count <= self . len( ) ) ;
215
214
// INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
@@ -489,23 +488,15 @@ where
489
488
/// # Ok::<(), Error>(())
490
489
/// ```
491
490
pub fn truncate ( & mut self , len : usize ) {
492
- if len >= self . len ( ) {
493
- return ;
491
+ if let Some ( count) = self . len ( ) . checked_sub ( len) {
492
+ // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
493
+ // equal to `self.len()`.
494
+ let ptr: * mut [ T ] = unsafe { self . dec_len ( count) } ;
495
+
496
+ // SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are
497
+ // valid elements whose ownership has been transferred to the caller.
498
+ unsafe { ptr:: drop_in_place ( ptr) } ;
494
499
}
495
-
496
- let drop_range = len..self . len ( ) ;
497
-
498
- // SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
499
- let ptr: * mut [ T ] = unsafe { self . get_unchecked_mut ( drop_range) } ;
500
-
501
- // SAFETY: By the above bounds check, it is guaranteed that `len < self.capacity()`.
502
- unsafe { self . set_len ( len) } ;
503
-
504
- // SAFETY:
505
- // - the dropped values are valid `T`s by the type invariant
506
- // - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
507
- // len, therefore we have exclusive access to [`new_len`, `old_len`)
508
- unsafe { ptr:: drop_in_place ( ptr) } ;
509
500
}
510
501
}
511
502
0 commit comments