fix: order large numbers by value in natural sort (#2714)

naturalCmp parsed digit runs with strconv.Atoi and fell back to a plain
string comparison when parsing failed. Numbers that do not fit in an int
(20 digits or more on 64-bit platforms) were therefore compared
lexicographically, so '10000000000000000000' sorted before '9'. This also
made the comparison non-transitive ('9' < '10' < '10000000000000000000'
< '9'), which slices.SortStableFunc does not support.

Compare the digit runs directly instead: strip leading zeros, compare by
length, then by digits, keeping the existing tie-break on the length of
the original run.

Co-authored-by: ybai08 <271969568+ybai08@users.noreply.github.com>
This commit is contained in:
Yang Baiandybai08 authored and GitHub committed 2026-10-30 00:52:11 +01:00
1 parent a9d6c5d834
commit 6f9b1879f3
2 files changed
+16 -9

No files matched your search

+10 -9
View File
@@ -11,7 +11,6 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv"
"strings" "strings"
"unicode" "unicode"
@@ -393,14 +392,16 @@ func naturalCmp(s1, s2 string) int {
tok2 := s2[lo2:hi2] tok2 := s2[lo2:hi2]
if isDigit1 && isDigit2 { if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(tok1) // compare the digits directly instead of parsing them, so that
num2, err2 := strconv.Atoi(tok2) // numbers too large for an int are still ordered by value
if err1 == nil && err2 == nil { num1 := strings.TrimLeft(tok1, "0")
if num1 != num2 { num2 := strings.TrimLeft(tok2, "0")
return cmp.Compare(num1, num2) if len(num1) != len(num2) {
} else if len(tok1) != len(tok2) { return cmp.Compare(len(num1), len(num2))
return cmp.Compare(len(tok1), len(tok2)) } else if num1 != num2 {
} return cmp.Compare(num1, num2)
} else if len(tok1) != len(tok2) {
return cmp.Compare(len(tok1), len(tok2))
} }
} }
+6
View File
@@ -399,6 +399,12 @@ func TestNaturalCmp(t *testing.T) {
{"foo0bar", "foo00bar", -1}, {"foo0bar", "foo00bar", -1},
{"foo1", "foo01", -1}, {"foo1", "foo01", -1},
{"foo1bar", "foo01bar", -1}, {"foo1bar", "foo01bar", -1},
{"9", "10000000000000000000", -1},
{"foo9", "foo10000000000000000000", -1},
{"9223372036854775807", "9223372036854775808", -1},
{"99999999999999999999", "100000000000000000000", -1},
{"100000000000000000000", "0100000000000000000000", -1},
{"100000000000000000000a", "100000000000000000000b", -1},
} }
for _, test := range tests { for _, test := range tests {