github.com/google/osv-scalibr@v0.4.1/semantic/version.go (about) 1 // Copyright 2025 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package semantic 16 17 import ( 18 "math/big" 19 ) 20 21 // Version provides an interface for sortable version strings. 22 type Version interface { 23 // CompareStr returns an integer representing the sort order of the given string 24 // when parsed as the concrete Version relative to the subject Version. 25 // 26 // The result will be 0 if v == w, -1 if v < w, or +1 if v > w. 27 // 28 // An error is returned if the given string is not a valid Version, with "valid" 29 // being dependent on the underlying ecosystem of the concrete Version. 30 CompareStr(str string) (int, error) 31 } 32 33 type components []*big.Int 34 35 func (components *components) Fetch(n int) *big.Int { 36 if len(*components) <= n { 37 return big.NewInt(0) 38 } 39 40 return (*components)[n] 41 } 42 43 func (components *components) Cmp(b components) int { 44 numberOfComponents := max(len(*components), len(b)) 45 46 for i := range numberOfComponents { 47 diff := components.Fetch(i).Cmp(b.Fetch(i)) 48 49 if diff != 0 { 50 return diff 51 } 52 } 53 54 return 0 55 }