-
Notifications
You must be signed in to change notification settings - Fork 155
/
util.go
83 lines (72 loc) · 2.2 KB
/
util.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Copyright 2020 The Qmgo Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package qmgo
import (
"math"
"strconv"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Now return Millisecond current time
func Now() time.Time {
return time.Unix(0, time.Now().UnixNano()/1e6*1e6)
}
// NewObjectID generates a new ObjectID.
// Watch out: the way it generates objectID is different from mgo
func NewObjectID() primitive.ObjectID {
return primitive.NewObjectID()
}
// SplitSortField handle sort symbol: "+"/"-" in front of field
// if "+", return sort as 1
// if "-", return sort as -1
func SplitSortField(field string) (key string, sort int32) {
sort = 1
key = field
if len(field) != 0 {
switch field[0] {
case '+':
key = strings.TrimPrefix(field, "+")
sort = 1
case '-':
key = strings.TrimPrefix(field, "-")
sort = -1
}
}
return key, sort
}
// CompareVersions compares two version number strings (i.e. positive integers separated by
// periods). Comparisons are done to the lesser precision of the two versions. For example, 3.2 is
// considered equal to 3.2.11, whereas 3.2.0 is considered less than 3.2.11.
//
// Returns a positive int if version1 is greater than version2, a negative int if version1 is less
// than version2, and 0 if version1 is equal to version2.
func CompareVersions(v1 string, v2 string) (int, error) {
n1 := strings.Split(v1, ".")
n2 := strings.Split(v2, ".")
for i := 0; i < int(math.Min(float64(len(n1)), float64(len(n2)))); i++ {
i1, err := strconv.Atoi(n1[i])
if err != nil {
return 0, err
}
i2, err := strconv.Atoi(n2[i])
if err != nil {
return 0, err
}
difference := i1 - i2
if difference != 0 {
return difference, nil
}
}
return 0, nil
}