github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/protobuf.go (about) 1 /* 2 Copyright 2023 Gravitational, Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "google.golang.org/protobuf/proto" 21 "google.golang.org/protobuf/protoadapt" 22 ) 23 24 // CloneProtoMsg returns a deep copy of msg. Modifying the returned 25 // protobuf message will not affect msg. If msg contains any empty 26 // slices, the returned copy will have nil slices instead. 27 func CloneProtoMsg[T protoadapt.MessageV1](msg T) T { 28 // github.com/golang/protobuf/proto.Clone panics when trying to 29 // copy a map[K]V where the type of V is a slice of anything 30 // other than byte. See https://github.com/gogo/protobuf/issues/14 31 msgV2 := protoadapt.MessageV2Of(msg) 32 msgV2 = proto.Clone(msgV2) 33 // this is safe as protoadapt.MessageV2Of will simply wrap the message 34 // with a type that implements the protobuf v2 API, and 35 // protoadapt.MessageV1Of will return the unwrapped message 36 return protoadapt.MessageV1Of(msgV2).(T) 37 }