/* * * Copyright 2024 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
// Package proto defines the protobuf codec. Importing this package will// register the codec.
package protoimport ()// Name is the name registered for the proto compressor.constName = "proto"func init() {encoding.RegisterCodecV2(&codecV2{})}// codec is a CodecV2 implementation with protobuf. It is the default codec for// gRPC.type codecV2 struct{}func ( *codecV2) ( any) ( mem.BufferSlice, error) { := messageV2Of()if == nil {returnnil, fmt.Errorf("proto: failed to marshal, message is %T, want proto.Message", ) }// Important: if we remove this Size call then we cannot use // UseCachedSize in MarshalOptions below. := proto.Size()// MarshalOptions with UseCachedSize allows reusing the result from the // previous Size call. This is safe here because: // // 1. We just computed the size. // 2. We assume the message is not being mutated concurrently. // // Important: If the proto.Size call above is removed, using UseCachedSize // becomes unsafe and may lead to incorrect marshaling. // // For more details, see the doc of UseCachedSize: // https://pkg.go.dev/google.golang.org/protobuf/proto#MarshalOptions := proto.MarshalOptions{UseCachedSize: true}ifmem.IsBelowBufferPoolingThreshold() { , := .Marshal()if != nil {returnnil, } = append(, mem.SliceBuffer()) } else { := mem.DefaultBufferPool() := .Get()if , := .MarshalAppend((*)[:0], ); != nil { .Put()returnnil, } = append(, mem.NewBuffer(, )) }return , nil}func ( *codecV2) ( mem.BufferSlice, any) ( error) { := messageV2Of()if == nil {returnfmt.Errorf("failed to unmarshal, message is %T, want proto.Message", ) } := .MaterializeToBuffer(mem.DefaultBufferPool())defer .Free()// TODO: Upgrade proto.Unmarshal to support mem.BufferSlice. Right now, it's not // really possible without a major overhaul of the proto package, but the // vtprotobuf library may be able to support this.returnproto.Unmarshal(.ReadOnlyData(), )}func messageV2Of( any) proto.Message {switch v := .(type) {caseprotoadapt.MessageV1:returnprotoadapt.MessageV2Of()caseprotoadapt.MessageV2:return }returnnil}func ( *codecV2) () string {returnName}
The pages are generated with Goldsv0.8.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.