kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/go/util/ptypes/ptypes.go (about) 1 /* 2 * Copyright 2016 The Kythe Authors. All rights reserved. 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 ptypes is a thin wrapper around the golang.org/protobuf/ptypes 18 // package that adds support for Kythe message types, and handles some type 19 // format conversions. 20 package ptypes // import "kythe.io/kythe/go/util/ptypes" 21 22 import ( 23 "sort" 24 "strings" 25 26 "github.com/golang/protobuf/proto" 27 "github.com/golang/protobuf/ptypes" 28 29 anypb "github.com/golang/protobuf/ptypes/any" 30 ) 31 32 // Any is an alias for the protocol buffer Any message type. 33 type Any = anypb.Any 34 35 // MarshalAny converts pb to a google.protobuf.Any message, fixing the URLs of 36 // Kythe protobuf types as needed. 37 func MarshalAny(pb proto.Message) (*anypb.Any, error) { 38 // The ptypes package vendors generated code for the Any type, so we have 39 // to convert the type. The pointers are convertible, but since we need to 40 // do surgery on the URL anyway, we just construct the output separately. 41 internalAny, err := ptypes.MarshalAny(pb) 42 if err != nil { 43 return nil, err 44 } 45 46 // Fix up messages in the Kythe namespace. 47 url := internalAny.TypeUrl 48 if name, _ := ptypes.AnyMessageName(internalAny); strings.HasPrefix(name, "kythe.") { 49 url = "kythe.io/proto/" + name 50 } 51 return &anypb.Any{ 52 TypeUrl: url, 53 Value: internalAny.Value, 54 }, nil 55 } 56 57 // UnmarshalAny unmarshals a google.protobuf.Any message into pb. 58 // This is an alias for ptypes.UnmarshalAny to save an import. 59 func UnmarshalAny(any *anypb.Any, pb proto.Message) error { 60 return ptypes.UnmarshalAny(any, pb) 61 } 62 63 // SortByTypeURL orders a slice of Any messages by their type URL, modifying 64 // the argument slice in-place. 65 func SortByTypeURL(msgs []*anypb.Any) { sort.Sort(byTypeURL(msgs)) } 66 67 type byTypeURL []*anypb.Any 68 69 func (b byTypeURL) Len() int { return len(b) } 70 func (b byTypeURL) Less(i, j int) bool { return b[i].TypeUrl < b[j].TypeUrl } 71 func (b byTypeURL) Swap(i, j int) { b[i], b[j] = b[j], b[i] }