-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.go
97 lines (81 loc) · 1.62 KB
/
utils.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
package mocrelay
import (
"context"
"fmt"
"slices"
)
func panicf(format string, a ...any) {
panic(fmt.Sprintf(format, a...))
}
func toPtr[T any](v T) *T { return &v }
func anySliceAs[T any](sli []any) ([]T, bool) {
if sli == nil {
return nil, true
}
ret := make([]T, len(sli))
for i, v := range sli {
vv, ok := v.(T)
if !ok {
return nil, false
}
ret[i] = vv
}
return ret, true
}
func sliceAllFunc[T any](vs []T, f func(v T) bool) bool {
return !slices.ContainsFunc(vs, func(v T) bool { return !f(v) })
}
func sendCtx[T any](ctx context.Context, ch chan<- T, v T) (sent bool) {
select {
case <-ctx.Done():
return false
case ch <- v:
return true
}
}
func trySendCtx[T any](ctx context.Context, ch chan<- T, v T) (sent bool) {
select {
case <-ctx.Done():
return false
case ch <- v:
return true
default:
return false
}
}
func sendClientMsgCtx(ctx context.Context, ch chan<- ClientMsg, msg ClientMsg) (sent bool) {
if IsNilClientMsg(msg) {
return
}
return sendCtx(ctx, ch, msg)
}
func sendServerMsgCtx(ctx context.Context, ch chan<- ServerMsg, msg ServerMsg) (sent bool) {
if IsNilServerMsg(msg) {
return
}
return sendCtx(ctx, ch, msg)
}
type bufCh[T any] chan T
func newBufCh[T any](items ...T) bufCh[T] {
ret := make(chan T, len(items))
for _, item := range items {
ret <- item
}
return ret
}
func newClosedBufCh[T any](items ...T) bufCh[T] {
ret := newBufCh(items...)
close(ret)
return ret
}
func validHexString(s string) bool {
if len(s) == 0 {
return false
}
for _, r := range s {
if !(('0' <= r && r <= '9') || ('a' <= r && r <= 'f')) {
return false
}
}
return true
}