Skip to main content

der_sort

Function der_sort 

Source
fn der_sort<T: DerOrd>(slice: &mut [T]) -> Result<(), Error>
Expand description

Sort a mut slice according to its DerOrd, returning any errors which might occur during the comparison.

Uses slice::sort_unstable_by (an O(n log n) introsort) rather than the stable slice::sort_by because the latter requires alloc, while this function must also work on heapless no_std targets where only core is available. Sorting unstably is fine here: two elements that compare Ordering::Equal under DerOrd have identical DER encodings, so their relative order does not affect the serialized output.

A previous implementation used a hand-rolled insertion sort. On adversarial reverse-sorted input that degrades to O(n^2), which let a crafted SET OF turn a single decode into a quadratic-time denial of service (see https://github.com/RustCrypto/formats/issues/2319).

DerOrd::der_cmp is fallible. Since the standard sort comparator must return Ordering rather than a Result, the first comparison error is captured and returned after the sort completes; on error the slice is left in an unspecified (but valid) order.