-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathequal.go
48 lines (42 loc) · 974 Bytes
/
equal.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
package typutil
import "bytes"
// Equal returns true if a and b are somewhat equal
func Equal(a, b any) bool {
// this is an approximate equal method, a==b can be true even if both aren't exactly the same type
if a == nil {
if b == nil {
return true
}
// reverse things so a is not nil
a, b = b, a
}
if typePriority(a) < typePriority(b) {
// if a has lower priority, reverse
a, b = b, a
}
b, _ = ToType(a, b)
switch av := a.(type) {
case []byte:
return bytes.Compare(av, b.([]byte)) == 0
default:
// hope this works, lol
return a == b
}
}
// typePriority returns a numeric value defining which type will have priority on the other
func typePriority(v any) int {
switch v.(type) {
case float32, float64:
return 4
case bool:
return 3
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr:
return 3
case string, []byte, *bytes.Buffer:
return 2
case nil:
return -1
default:
return 1 // ??
}
}