pub fn natural_sort(a: &str, b: &str) -> OrderingExpand description
Performs natural sorting comparison between two strings.
Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations. For example, “file2” comes before “file10” (unlike standard lexicographic sorting).
§Characteristics
- Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase
- Numbers are compared by numeric value, not character by character
- Leading zeros affect ordering when numeric values are equal
- Can handle numbers larger than u128::MAX (falls back to string comparison)
- When strings are equal case-insensitively, lowercase is prioritized (lowercase < uppercase)
§Algorithm
The function works by:
- Processing strings character by character in a case-insensitive manner
- When encountering digits, treating consecutive digits as a single number
- Comparing numbers by their numeric value rather than lexicographically
- For non-numeric characters, using case-insensitive comparison
- If everything is equal case-insensitively, using case-sensitive comparison as final tie-breaker