-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathversion.go
More file actions
65 lines (57 loc) · 1.98 KB
/
Copy pathversion.go
File metadata and controls
65 lines (57 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package command
import "bytes"
// versionLess compares keys as version strings (-V): runs of digits compare by
// numeric value so v1.2 < v1.10, while other runs compare as bytes.
func versionLess(a, b []byte) bool {
for len(a) > 0 && len(b) > 0 {
cmp, restA, restB := compareChunk(a, b)
if cmp != 0 {
return cmp < 0
}
a, b = restA, restB
}
return len(a) < len(b)
}
// compareChunk compares one aligned chunk from each key and returns its sign
// plus both keys advanced past the consumed bytes.
func compareChunk(a, b []byte) (int, []byte, []byte) {
if isDigit(keyByte(a[0])) && isDigit(keyByte(b[0])) {
return compareNumberRun(a, b)
}
return int(a[0]) - int(b[0]), a[1:], b[1:]
}
// compareNumberRun compares the leading digit run of each key numerically
// (ignoring leading zeros) and returns the sign plus both keys advanced past
// their runs.
func compareNumberRun(a, b []byte) (int, []byte, []byte) {
runA, restA := takeDigits(a)
runB, restB := takeDigits(b)
return bytes.Compare(runA, runB), restA, restB
}
// takeDigits splits key into its leading digit run and the remaining bytes.
// The run is stripped of leading zeros and left-padded so numeric magnitude
// compares by length then bytes.
func takeDigits(key []byte) ([]byte, []byte) {
i := 0
for i < len(key) && isDigit(keyByte(key[i])) {
i++
}
return padLeft(bytes.TrimLeft(key[:i], "0")), key[i:]
}
// padLeft left-pads a stripped digit run to a fixed width so bytes.Compare
// orders by numeric magnitude. Runs longer than the width keep full precision
// because longer runs are always the larger number.
func padLeft(run []byte) []byte {
const width = 20
if len(run) >= width {
return run
}
return append(bytes.Repeat([]byte{'0'}, width-len(run)), run...)
}
// keyByte is a single byte of a version-sort comparison key, classified as
// digit or non-digit to select the chunk comparison.
type keyByte byte
// isDigit reports whether c is an ASCII digit.
func isDigit(c keyByte) bool {
return c >= '0' && c <= '9'
}