-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmp.go
122 lines (100 loc) · 2.52 KB
/
cmp.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Copyright (c) 2022 The Go-Enjin 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 cmp
import (
"fmt"
"time"
"github.com/go-corelibs/values"
)
func Cmp[T comparable](a, b interface{}) (same bool, err error) {
if ac, ok := a.(T); ok {
if bc, ok := b.(T); ok {
same = ac == bc
return
}
}
err = fmt.Errorf("error cmp.Cmp - inconsistent types: %T vs %T", a, b)
return
}
func Compare(a, b interface{}) (same bool, err error) {
if values.TypeOf(a) != values.TypeOf(b) {
err = fmt.Errorf("incompatible types for comparison: %T vs %T", a, b)
return
}
switch ta := a.(type) {
case nil,
string,
float32, float64,
int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64:
switch tb := b.(type) {
case nil,
string,
float32, float64,
int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64:
same = ta == tb
}
case time.Time:
same = ta.Unix() == b.(time.Time).Unix()
case time.Duration:
same = ta.String() == b.(time.Duration).String()
default:
err = fmt.Errorf("unsupported type for comparison: %T", a)
}
return
}
func Less(a, b interface{}) (less bool, err error) {
if values.TypeOf(a) != values.TypeOf(b) {
err = fmt.Errorf("incompatible types for (less) comparison: %T vs %T", a, b)
return
}
switch ta := a.(type) {
case nil:
less = false
case string:
less = ta < b.(string)
case float32:
less = ta < b.(float32)
case float64:
less = ta < b.(float64)
case int:
less = ta < b.(int)
case int8:
less = ta < b.(int8)
case int16:
less = ta < b.(int16)
case int32:
less = ta < b.(int32)
case int64:
less = ta < b.(int64)
case uint:
less = ta < b.(uint)
case uint8:
less = ta < b.(uint8)
case uint16:
less = ta < b.(uint16)
case uint32:
less = ta < b.(uint32)
case uint64:
less = ta < b.(uint64)
case time.Time:
less = ta.Before(b.(time.Time))
case time.Duration:
less = ta.Seconds() < b.(time.Duration).Seconds()
default:
err = fmt.Errorf("unsupported type for (less) comparison: %T", a)
}
return
}