diff --git a/util/cmpver/version.go b/util/cmpver/version.go index 2a30f0653..972c7b95f 100644 --- a/util/cmpver/version.go +++ b/util/cmpver/version.go @@ -24,6 +24,20 @@ import ( "strings" ) +// Less reports whether v1 is less than v2. +// +// Note that "12" is less than "12.0". +func Less(v1, v2 string) bool { + return Compare(v1, v2) < 0 +} + +// LessEq reports whether v1 is less than or equal to v2. +// +// Note that "12" is less than "12.0". +func LessEq(v1, v2 string) bool { + return Compare(v1, v2) <= 0 +} + func isnum(r rune) bool { return r >= '0' && r <= '9' } @@ -32,9 +46,12 @@ func notnum(r rune) bool { return !isnum(r) } -// Compare returns an integer comparing two strings as version -// numbers. The result will be 0 if v1==v2, -1 if v1 < v2, and +1 if -// v1 > v2. +// Compare returns an integer comparing two strings as version numbers. +// The result will be -1, 0, or 1 representing the sign of v1 - v2: +// +// Compare(v1, v2) < 0 if v1 < v2 +// == 0 if v1 == v2 +// > 0 if v1 > v2 func Compare(v1, v2 string) int { var ( f1, f2 string diff --git a/util/cmpver/version_test.go b/util/cmpver/version_test.go index ecfac89e2..8a3e470d1 100644 --- a/util/cmpver/version_test.go +++ b/util/cmpver/version_test.go @@ -163,16 +163,31 @@ func TestCompare(t *testing.T) { t.Run(test.name, func(t *testing.T) { got := cmpver.Compare(test.v1, test.v2) if got != test.want { - t.Errorf("Compare(%v, %v) = %v, want %v", test.v1, test.v2, got, test.want) + t.Errorf("Compare(%q, %q) = %v, want %v", test.v1, test.v2, got, test.want) } + // Reversing the comparison should reverse the outcome. got2 := cmpver.Compare(test.v2, test.v1) if got2 != -test.want { - t.Errorf("Compare(%v, %v) = %v, want %v", test.v2, test.v1, got2, -test.want) + t.Errorf("Compare(%q, %q) = %v, want %v", test.v2, test.v1, got2, -test.want) } + + if got, want := cmpver.Less(test.v1, test.v2), test.want < 0; got != want { + t.Errorf("Less(%q, %q) = %v, want %v", test.v1, test.v2, got, want) + } + if got, want := cmpver.Less(test.v2, test.v1), test.want > 0; got != want { + t.Errorf("Less(%q, %q) = %v, want %v", test.v2, test.v1, got, want) + } + if got, want := cmpver.LessEq(test.v1, test.v2), test.want <= 0; got != want { + t.Errorf("LessEq(%q, %q) = %v, want %v", test.v1, test.v2, got, want) + } + if got, want := cmpver.LessEq(test.v2, test.v1), test.want >= 0; got != want { + t.Errorf("LessEq(%q, %q) = %v, want %v", test.v2, test.v1, got, want) + } + // Check that version comparison does not allocate. if n := testing.AllocsPerRun(100, func() { cmpver.Compare(test.v1, test.v2) }); n > 0 { - t.Errorf("Compare(%v, %v) got %v allocs per run", test.v1, test.v2, n) + t.Errorf("Compare(%q, %q) got %v allocs per run", test.v1, test.v2, n) } }) }