PHP的version_compare是对比两个「PHP 规范化」的版本数字字符串。
mixed version_compare ( string $version1,string $version2 [,string $operator ] )
使用golang实现其中一部分常用的功能。
package util import ( "strings" "strconv" ) // 该函数比较两个版本号是否相等,是否大于或小于的关系 // 返回值:0表示v1与v2相等;1表示v1大于v2;2表示v1小于v2 func Compare(v1,v2 string) int { // 替换一些常见的版本符号 replaceMap := map[string]string{"V":"","v": "","-": ".",} //keywords := {"alpha,beta,rc,p"} for k,v := range replaceMap { if strings.Contains(v1,k) { strings.Replace(v1,k,v,-1) } if strings.Contains(v2,k) { strings.Replace(v2,-1) } } verStr1 := strings.Split(v1,".") verStr2 := strings.Split(v2,".") ver1 := strSlice2IntSlice(verStr1) ver2 := strSlice2IntSlice(verStr2) // 找出v1和v2哪一个最短 var shorter int if len(ver1) > len(ver2) { shorter = len(ver2) } else { shorter = len(ver1) } // 循环比较 for i := 0; i < shorter; i++ { if ver1[i] == ver2[i] { if shorter-1 == i { if len(ver1) == len(ver2) { return 0 } else { // @todo check for keywords if len(ver1) > len(ver2) { return 1 } else { return 2 } } } } else if ver1[i] > ver2[i] { return 1 } else { return 2 } } return -1 } func strSlice2IntSlice(strs []string) []int64 { if len(strs) == 0 { return []int64{} } retInt := make([]int64,len(strs)) for _,str:=range strs { i,err := strconv.ParseInt(str,10,64) if err == nil { retInt = append(retInt,i) } } return retInt } func VersionCompare(v1,v2,operator string) bool { com := Compare(v1,v2) switch operator { case "==": if com == 0 { return true } case "<": if com == 2 { return true } case ">": if com == 1 { return true } case "<=": if com == 0 || com == 2 { return true } case ">=": if com == 0 || com == 1{ return true } } return false }
测试单元:
package version import ( "testing" version "github.com/mcuadros/go-version" ) var ( v1 = "2.0.1" v1_1 = "2.0.1.1" v2 = "2.1.1" v3 = "2.10.22.1" v4 = "2.09.22.2" v5 = "2.9.22.2" ) // go test -test.bench=".*" func Benchmark_MyVersion(b *testing.B) { for i:=0;i<b.N ;i++ { VersionCompare("2.3.1","2.1.3.4",">=") } } func Benchmark_GoVersion(b *testing.B) { for i:=0;i<1000000 ;i++ { version.Compare("2.3.1",">=") } } // 该函数比较两个版本号是否相等,是否大于或小于的关系 // 返回值:0表示v1与v2相等;1表示v1大于v2;2表示v1小于v2 func TestCompare(t *testing.T) { if 0 != Compare(v1,v1) { t.Errorf("v1 %s == v1 %s ",v1,v1) } if 1 != Compare(v2,v1) { t.Errorf("v2 %s > v1 %s",v1) } if 2 != Compare(v1,v2) { t.Errorf("v1 %s < v2 %s",v2) } } func TestVersionCompare(t *testing.T) { if !VersionCompare(v1,v1_1,"<") { t.Errorf("v1 %s < v1_1 %s ",v1_1) } if !VersionCompare(v2,">") { t.Errorf("v2 %s < v1_1 %s ",">=") { t.Errorf("v2 %s >= v1 %s ",v1) } if !VersionCompare(v1,"<=") { t.Errorf("v1 %s >= v2 %s ",v2) } if !VersionCompare(v1,"==") { t.Errorf("v1 %s == v1 %s ",v1) } if !VersionCompare(v3,v4,">") { t.Errorf("v3 %s > v4 %s ",v3,v4) } if !VersionCompare(v3,v5,">") { t.Errorf("v3 %s > v5 %s ",v5) } /*if !VersionCompare(v3,"<=") { t.Errorf("v3 %s > v5 %s ",v5) }*/ if !VersionCompare(v4,"==") { t.Errorf("v4 %s == v5 %s ",v5) } }
该代码只是实现其中的『<,>,<=,>=,==』。