-
Notifications
You must be signed in to change notification settings - Fork 0
/
stdcomparabletypes.go
83 lines (69 loc) · 2.52 KB
/
stdcomparabletypes.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 2015 Google Inc. All Rights Reserved.
//
// 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 dataselect
import (
"strings"
"time"
)
// ----------------------- Standard Comparable Types ------------------------
// These types specify how given value should be compared
// They all implement ComparableValueInterface
// You can convert basic types to these types to supprt auto sorting etc.
// If you cant find your type compare here you will have to implement it yourself :)
type StdComparableInt int
func (self StdComparableInt) Compare(otherV ComparableValue) int {
other := otherV.(StdComparableInt)
return intsCompare(int(self), int(other))
}
type StdComparableString string
func (self StdComparableString) Compare(otherV ComparableValue) int {
other := otherV.(StdComparableString)
return strings.Compare(string(self), string(other))
}
// StdComparableRFC3339Timestamp takes RFC3339 Timestamp strings and compares them as TIMES. In case of time parsing error compares values as strings.
type StdComparableRFC3339Timestamp string
func (self StdComparableRFC3339Timestamp) Compare(otherV ComparableValue) int {
other := otherV.(StdComparableRFC3339Timestamp)
// try to compare as timestamp (earlier = smaller)
selfTime, err1 := time.Parse(time.RFC3339, string(self))
otherTime, err2 := time.Parse(time.RFC3339, string(other))
if err1 != nil || err2 != nil {
// in case of timestamp parsing failure just compare as strings
return strings.Compare(string(self), string(other))
} else {
return ints64Compare(selfTime.Unix(), otherTime.Unix())
}
}
type StdComparableTime time.Time
func (self StdComparableTime) Compare(otherV ComparableValue) int {
other := otherV.(StdComparableTime)
return ints64Compare(time.Time(self).Unix(), time.Time(other).Unix())
}
// Int comparison functions. Similar to strings.Compare.
func intsCompare(a, b int) int {
if a > b {
return 1
} else if a == b {
return 0
}
return -1
}
func ints64Compare(a, b int64) int {
if a > b {
return 1
} else if a == b {
return 0
}
return -1
}