Skip to content

Commit 644550f

Browse files
committed
Improve panic message and surrounding documentation for Ord violations
The new sort implementations have the ability to detect Ord violations in many cases. This commit improves the message in a way that should help users realize what went wrong in their program.
1 parent 3942254 commit 644550f

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

library/core/src/slice/sort/shared/smallsort.rs

+19-4
Original file line numberDiff line numberDiff line change
@@ -834,9 +834,10 @@ unsafe fn bidirectional_merge<T: FreezeMarker, F: FnMut(&T, &T) -> bool>(
834834
right = right.add((!left_nonempty) as usize);
835835
}
836836

837-
// We now should have consumed the full input exactly once. This can
838-
// only fail if the comparison operator fails to be Ord, in which case
839-
// we will panic and never access the inconsistent state in dst.
837+
// We now should have consumed the full input exactly once. This can only fail if the
838+
// user-provided comparison operator fails implements a strict weak ordering as required by
839+
// Ord incorrectly, in which case we will panic and never access the inconsistent state in
840+
// dst.
840841
if left != left_end || right != right_end {
841842
panic_on_ord_violation();
842843
}
@@ -845,7 +846,21 @@ unsafe fn bidirectional_merge<T: FreezeMarker, F: FnMut(&T, &T) -> bool>(
845846

846847
#[inline(never)]
847848
fn panic_on_ord_violation() -> ! {
848-
panic!("Ord violation");
849+
// This is indicative of a logic bug in the user-provided comparison function or Ord
850+
// implementation. They are expected to implement a total order as explained in the Ord
851+
// documentation.
852+
//
853+
// By raising this panic we inform the user, that they have a logic bug in their program. If a
854+
// strict weak ordering is not given, the concept of comparison based sorting makes no sense.
855+
// E.g.: a < b < c < a
856+
//
857+
// The Ord documentation requires users to implement a total order, arguably that's
858+
// unnecessarily strict in the context of sorting. Issues only arise if the weaker requirement
859+
// of a strict weak ordering is violated.
860+
//
861+
// The panic message talks about a total order because that's what the Ord documentation talks
862+
// about and requires, so as to not confuse users.
863+
panic!("user-provided comparison function does not correctly implement a total order");
849864
}
850865

851866
#[must_use]

0 commit comments

Comments
 (0)