-
Notifications
You must be signed in to change notification settings - Fork 0
/
ptr.go
72 lines (61 loc) · 1.49 KB
/
ptr.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
package ptr
import (
"github.com/go-board/std/cmp"
)
func zero[T any]() (v T) { return }
// Ref return reference of value
func Ref[T any](t T) *T { return &t }
// RefOrNil return reference of value if it not the zero value, else return nil
func RefOrNil[T comparable](t T) *T {
if t == zero[T]() {
return nil
}
return &t
}
// ValueOr return value of pointer if not nil, else return default value.
func ValueOr[T any](v *T, d T) T {
if v == nil {
return d
}
return *v
}
// ValueOrZero return value of pointer if not nil, else return zero value.
func ValueOrZero[T any](v *T) T {
return ValueOr(v, zero[T]())
}
func OrZero[T any](v *T) *T {
if v == nil {
return Ref(zero[T]())
}
return v
}
// Compare compares two pointer. If both non-nil, compare underlying data,
// if both nil, return 0, non-nil pointer is always greater than nil pointer.
func Compare[T cmp.Ordered](l, r *T) int {
return CompareBy(l, r, cmp.Compare[T])
}
func CompareBy[T any](l, r *T, cmp func(T, T) int) int {
if l != nil && r != nil {
return cmp(*l, *r)
}
if l == nil && r == nil {
return 0
}
if l != nil {
return +1
}
return -1
}
// Equal test whether two pointer are equal. If both non-nil, test underlying data,
// if both nil, return true, else return false
func Equal[T comparable](l, r *T) bool {
return EqualBy(l, r, cmp.Equal[T])
}
func EqualBy[T any](l, r *T, eq func(T, T) bool) bool {
if l != nil && r != nil {
return eq(*l, *r)
} else if l == nil && r == nil {
return true
}
return false
}