Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,6 @@ func allZero(segs []int64) bool {
}

// isNumericIdentifier reports whether s consists entirely of ASCII digits.
// Per the semver spec, numeric identifiers must not have leading zeroes,
// so a longer string always represents a larger value and lexicographic
// order equals numeric order for strings of the same length.
func isNumericIdentifier(s string) bool {
if s == "" {
return false
Expand All @@ -276,8 +273,10 @@ func isNumericIdentifier(s string) bool {

// compareNumericIdentifiers compares two all-digit strings by value without
// parsing them into a fixed-width integer type, correctly handling values
// larger than math.MaxInt64.
// larger than math.MaxInt64 and leading zeroes accepted by NewVersion.
func compareNumericIdentifiers(a, b string) int {
a = strings.TrimLeft(a, "0")
b = strings.TrimLeft(b, "0")
if len(a) != len(b) {
if len(a) > len(b) {
return 1
Expand Down
27 changes: 27 additions & 0 deletions version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -917,3 +917,30 @@ func BenchmarkVersionCompareV2(b *testing.B) {
v.Compare(o)
}
}

func TestComparePrereleaseLeadingZeros(t *testing.T) {
cases := []struct {
a, b string
want int
}{
{"01", "1", 0},
{"000", "0", 0},
{"001", "2", -1},
{"09", "10", -1},
{"0009223372036854775808", "9223372036854775807", 1},
{"0009223372036854775808", "9223372036854775808", 0},
{"00099999999999999999999", "100000000000000000000", -1},
}
for _, tc := range cases {
t.Run(tc.a+"/"+tc.b, func(t *testing.T) {
a := Must(NewVersion("1.0.0-" + tc.a))
b := Must(NewVersion("1.0.0-" + tc.b))
if got := a.Compare(b); got != tc.want {
t.Errorf("Compare = %d, want %d", got, tc.want)
}
if got := b.Compare(a); got != -tc.want {
t.Errorf("reverse Compare = %d, want %d", got, -tc.want)
}
})
}
}