Skip to content

Commit c710461

Browse files
committed
Added some unsafety documentation to partition_equal
1 parent c471519 commit c710461

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/libcore/slice/sort.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -435,15 +435,17 @@ where
435435
// Find the first pair of out-of-order elements.
436436
let mut l = 0;
437437
let mut r = v.len();
438+
439+
// SAFETY: The unsafety below involves indexing an array.
440+
// For the first one: we already do the bound checking here with `l<r`.
441+
// For the secondn one: the minimum value for `l` is 0 and the maximum value for `r` is `v.len().`
438442
unsafe {
439443
// Find the first element greater than or equal to the pivot.
440-
// SAFETY: We already do the bound checking here with `l<r`.
441444
while l < r && is_less(v.get_unchecked(l), pivot) {
442445
l += 1;
443446
}
444447

445448
// Find the last element smaller that the pivot.
446-
// SAFETY: The minimum value for `l` is 0 and the maximum value for `r` is `v.len().`
447449
while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
448450
r -= 1;
449451
}
@@ -477,6 +479,7 @@ where
477479

478480
// Read the pivot into a stack-allocated variable for efficiency. If a following comparison
479481
// operation panics, the pivot will be automatically written back into the slice.
482+
// SAFETY: The pointer here is valid because it is obtained from a reference to a slice.
480483
let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
481484
let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
482485
let pivot = &*tmp;
@@ -485,15 +488,16 @@ where
485488
let mut l = 0;
486489
let mut r = v.len();
487490
loop {
491+
// SAFETY: The unsafety below involves indexing an array.
492+
// For the first one: we already do the bound checking here with `l<r`.
493+
// For the second one: the minimum value for `l` is 0 and the maximum value for `r` is `v.len().`
488494
unsafe {
489495
// Find the first element greater than the pivot.
490-
// SAFETY: We already do the bound checking here with `l<r`
491496
while l < r && !is_less(pivot, v.get_unchecked(l)) {
492497
l += 1;
493498
}
494499

495500
// Find the last element equal to the pivot.
496-
// SAFETY: The minimum value for `l` is 0 and the maximum value for `r` is `v.len().`
497501
while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
498502
r -= 1;
499503
}

0 commit comments

Comments
 (0)