-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric.go
More file actions
79 lines (74 loc) · 1.75 KB
/
Copy pathgeneric.go
File metadata and controls
79 lines (74 loc) · 1.75 KB
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
package protox
import "google.golang.org/protobuf/proto"
// Clone creates a deep copy of a protobuf message.
//
// Parameters:
// - m: the message to clone.
//
// Returns:
// - M: a deep copy of the input message.
func Clone[M proto.Message](m M) M {
return proto.Clone(m).(M)
}
// CloneSlice creates a deep copy of a slice of protobuf messages.
// If the input slice is nil, it returns nil.
//
// Parameters:
// - s: the slice of messages to clone.
//
// Returns:
// - S: a new slice containing deep copies of the input messages.
func CloneSlice[S ~[]M, M proto.Message](s S) S {
var zero S
if s == nil {
return zero
}
r := make(S, 0, len(s))
for _, m := range s {
r = append(r, Clone(m))
}
return r
}
// MessageSlice converts a typed slice of protobuf messages to a slice of
// the proto.Message interface.
// If the input slice is nil, it returns nil.
//
// Parameters:
// - s: the typed slice of messages.
//
// Returns:
// - []proto.Message: the converted slice of interface values.
func MessageSlice[S []E, E proto.Message](s S) []proto.Message {
if s == nil {
return nil
}
r := make([]proto.Message, 0, len(s))
for _, e := range s {
r = append(r, e)
}
return r
}
// ProtoSlice converts a slice of proto.Message interface values to a typed
// slice of a specific message type.
// Elements that do not match the target type are skipped.
// If the input slice is nil, it returns nil.
//
// Parameters:
// - s: the slice of proto.Message interface values.
//
// Returns:
// - S: the typed slice containing only elements of type E.
func ProtoSlice[S []E, E proto.Message](s []proto.Message) S {
if s == nil {
return nil
}
r := make(S, 0, len(s))
for _, e := range s {
p, ok := e.(E)
if !ok {
continue
}
r = append(r, p)
}
return r
}