From 2604d2075715ec3ecd11c526d86b75ee8947f2ec Mon Sep 17 00:00:00 2001
From: yanghui <yanghui@aiotlink.com>
Date: 星期五, 14 五月 2021 15:25:09 +0800
Subject: [PATCH] version compare

---
 version.go |   55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 55 insertions(+), 0 deletions(-)

diff --git a/version.go b/version.go
index b0aa2e0..84b00eb 100644
--- a/version.go
+++ b/version.go
@@ -4,7 +4,10 @@
 	"encoding/json"
 	"flag"
 	"fmt"
+	"math"
 	"os"
+	"strconv"
+	"strings"
 )
 
 var (
@@ -35,3 +38,55 @@
 		}
 	}
 }
+
+func VersionCode2Name(version int64) (string, error) {
+	if version < 0 {
+		return "", errors.New("Version can't be negetive")
+	}
+
+	majorVersion := version >> 32
+	minorVersion := (version >> 16) & 0xffff
+	buildNumber := version & 0xffff
+
+	name := fmt.Sprintf("%d.%d.%d", majorVersion, minorVersion, buildNumber)
+
+	return name, nil
+}
+
+func VersionName2Code(version string) (int64, error) {
+	subVersions := strings.Split(version, ".")
+	if len(subVersions) != 3 {
+		return 0, errors.New("Incorrect version format, version formats like 1.12.3")
+	}
+
+	majorVersion, err := strconv.ParseInt(subVersions[0], 10, 64)
+	if nil != err {
+		return 0, errors.New(version + " major part can't be parsed, version formats like 1.12.3")
+	}
+
+	minorVersion, err := strconv.ParseInt(subVersions[1], 10, 64)
+	if nil != err {
+		return 0, errors.New(version + " minor part can't be parsed, version formats like 1.12.3")
+	}
+
+	buildNumber, err := strconv.ParseInt(subVersions[2], 10, 64)
+	if nil != err {
+		return 0, errors.New(version + " build number part can't be parsed, version formats like 1.12.3")
+	}
+
+	if majorVersion > math.MaxUint16 {
+		return 0, errors.New(version + " major version too large, max value is:" + strconv.Itoa(math.MaxUint16))
+	}
+
+	if minorVersion > math.MaxUint16 {
+		return 0, errors.New(version + " minor version too large, max value is:" + strconv.Itoa(math.MaxUint16))
+	}
+
+	if buildNumber > math.MaxUint16 {
+		return 0, errors.New(version + " build number too large, max value is:" + strconv.Itoa(math.MaxUint16))
+	}
+
+	num := (majorVersion << 32) | (minorVersion << 16) | buildNumber
+
+	return num, nil
+}

--
Gitblit v1.8.0