-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathother.go
86 lines (76 loc) · 1.45 KB
/
other.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
package genh
import (
"reflect"
"go.oneofone.dev/genh/internal"
)
type (
Signed = internal.Signed
Unsigned = internal.Unsigned
Integer = internal.Integer
Float = internal.Float
Complex = internal.Complex
Ordered = internal.Ordered
EncoderType = internal.EncoderType
DecoderType = internal.DecoderType
)
// ValuesToPtrs converts a slice of values to a slice of pointers
// optionally copying the values instead of pointing to them in the original slice.
func ValuesToPtrs[T any](vals []T, copy bool) []*T {
out := make([]*T, 0, len(vals))
for i := range vals {
var v *T
if copy {
cp := vals[i]
v = &cp
} else {
v = &vals[i]
}
out = append(out, v)
}
return out
}
func PtrsToValues[T any](vals []*T) []T {
out := make([]T, 0, len(vals))
for i := range vals {
v := vals[i]
out = append(out, *v)
}
return out
}
func Iff[T any](cond bool, a, b T) T {
if cond {
return a
}
return b
}
func IffFn[T any](cond bool, a, b func() T) T {
if cond {
return a()
}
return b()
}
func FirstNonZero[T any](args ...T) T {
for _, arg := range args {
if v := reflect.ValueOf(arg); v.IsValid() && !v.IsZero() {
return arg
}
}
return args[0]
}
func FirstNonZeroPtr[T any](args ...*T) *T {
for _, arg := range args {
if arg != nil {
return arg
}
}
return nil
}
func FirstNonZeroCmp[T comparable](args ...T) T {
var zero T
for _, arg := range args {
if arg != zero {
return arg
}
}
return zero
}