/
helpers.go
102 lines (89 loc) · 2.04 KB
/
helpers.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
package apstra
import (
"encoding/json"
"fmt"
"io"
"net"
"reflect"
"sync"
"time"
"github.com/google/uuid"
)
func pp(in interface{}, out io.Writer) error {
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
err := enc.Encode(in)
return err
}
// ourIpForPeer returns a *net.IP representing the local interface selected by
// the system for talking to the passed *net.IP. The returned value might also
// be the best choice for that peer to reach us.
func ourIpForPeer(them net.IP) (*net.IP, error) {
c, err := net.Dial("udp4", them.String()+":1")
if err != nil {
return nil, err
}
return &c.LocalAddr().(*net.UDPAddr).IP, c.Close()
}
func immediateTicker(interval time.Duration) *time.Ticker {
nc := make(chan time.Time, 1)
ticker := time.NewTicker(interval)
oc := ticker.C
go func() {
nc <- time.Now()
for tm := range oc {
nc <- tm
}
}()
ticker.C = nc
return ticker
}
func itemInSlice[A comparable](item A, slice []A) bool {
for i := range slice {
if item == slice[i] {
return true
}
}
return false
}
var (
uuidInit bool
uuidInitMutex sync.Mutex
)
// initUUID sets the "hardware address" used for generating UUIDv1 strings to "apstra"
func initUUID() {
uuidInitMutex.Lock()
defer uuidInitMutex.Unlock()
if !uuidInit {
uuid.SetNodeID([]byte("apstra"))
uuidInit = true
}
}
// uuid1AsObjectId returns a new UUIDv1 string as an ObjectId
func uuid1AsObjectId() (ObjectId, error) {
initUUID()
uuid1, err := uuid.NewUUID()
if err != nil {
return "", fmt.Errorf("failed while invoking uuid>NewUUID() - %w", err)
}
return ObjectId(uuid1.String()), nil
}
func toPtr[A any](a A) *A {
return &a
}
func stringerPtrToStringPtr(in fmt.Stringer) *string {
if in == nil {
return nil
}
// this interesting thing checks to make sure this thing is really nil...
if reflect.ValueOf(in).Kind() == reflect.Ptr && reflect.ValueOf(in).IsNil() {
return nil
}
return toPtr(in.String())
}
func featureSwitchEnumFromStringPtr(in *string) *FeatureSwitchEnum {
if in == nil {
return nil
}
return FeatureSwitchEnums.Parse(*in)
}