Created
December 22, 2017 02:36
-
-
Save siteshen/7c310a004aafd2946957c6bfc411acbf to your computer and use it in GitHub Desktop.
A simple version implementation in in Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package version | |
import ( | |
"strconv" | |
"strings" | |
) | |
type Version struct { | |
Major int | |
Minor int | |
Patch int | |
} | |
func parseVersion(s string) *Version { | |
strs := strings.SplitN(s, ".", 3) | |
major, minor, patch := "", "", "" | |
switch len(strs) { | |
case 1: | |
major = strs[0] | |
case 2: | |
major, minor = strs[0], strs[1] | |
case 3: | |
major, minor, patch = strs[0], strs[1], strs[2] | |
} | |
v := Version{ | |
Major: SafeParseInt(major), | |
Minor: SafeParseInt(minor), | |
Patch: SafeParseInt(patch), | |
} | |
return &v | |
} | |
func ParseVersion(s string) (v *Version) { | |
return parseVersion(s) | |
} | |
// Cmp compares the version represented by v1 and v2 and returns: | |
// | |
// -1 if v1 < v2 | |
// 0 if v1 == v2 | |
// +1 if v1 > v2 | |
// | |
func (v1 *Version) Cmp(v2 *Version) int { | |
return v1.compare(v2) | |
} | |
// GreaterThan returns true when v1 > v2. | |
func (v1 *Version) GreaterThan(v2 *Version) bool { | |
return v1.compare(v2) > 0 | |
} | |
// GreaterThanOrEqual returns true when v1 >= v2. | |
func (v1 *Version) GreaterThanOrEqual(v2 *Version) bool { | |
return v1.compare(v2) >= 0 | |
} | |
// Equal returns true when v1 == v2. | |
func (v1 *Version) Equal(v2 *Version) bool { | |
return v1.compare(v2) == 0 | |
} | |
// LessThanOrEqual returns true when v1 <= v2. | |
func (v1 *Version) LessThanOrEqual(v2 *Version) bool { | |
return v1.compare(v2) <= 0 | |
} | |
// LessThan returns true when v1 < v2. | |
func (v1 *Version) LessThan(v2 *Version) bool { | |
return v1.compare(v2) < 0 | |
} | |
func (v1 *Version) compare(v2 *Version) int { | |
switch { | |
case v1.Major > v2.Major: | |
return 1 | |
case v1.Major < v2.Major: | |
return -1 | |
} | |
switch { | |
case v1.Minor > v2.Minor: | |
return 1 | |
case v1.Minor < v2.Minor: | |
return -1 | |
} | |
switch { | |
case v1.Patch > v2.Patch: | |
return 1 | |
case v1.Patch < v2.Patch: | |
return -1 | |
} | |
return 0 | |
} | |
// SafeParseInt interprets a string s as int safely, i.e., ignore any parse error. | |
func SafeParseInt(s string) (i int) { | |
i, _ = strconv.Atoi(s) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment