github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/runtime/types_proto.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors. 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 runtime 18 19 import ( 20 "fmt" 21 ) 22 23 type ProtobufMarshaller interface { 24 MarshalTo(data []byte) (int, error) 25 } 26 27 type ProtobufReverseMarshaller interface { 28 MarshalToSizedBuffer(data []byte) (int, error) 29 } 30 31 // NestedMarshalTo allows a caller to avoid extra allocations during serialization of an Unknown 32 // that will contain an object that implements ProtobufMarshaller or ProtobufReverseMarshaller. 33 func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64) (int, error) { 34 // Calculate the full size of the message. 35 msgSize := m.Size() 36 if b != nil { 37 msgSize += int(size) + sovGenerated(size) + 1 38 } 39 40 // Reverse marshal the fields of m. 41 i := msgSize 42 i -= len(m.ContentType) 43 copy(data[i:], m.ContentType) 44 i = encodeVarintGenerated(data, i, uint64(len(m.ContentType))) 45 i-- 46 data[i] = 0x22 47 i -= len(m.ContentEncoding) 48 copy(data[i:], m.ContentEncoding) 49 i = encodeVarintGenerated(data, i, uint64(len(m.ContentEncoding))) 50 i-- 51 data[i] = 0x1a 52 if b != nil { 53 if r, ok := b.(ProtobufReverseMarshaller); ok { 54 n1, err := r.MarshalToSizedBuffer(data[:i]) 55 if err != nil { 56 return 0, err 57 } 58 i -= int(size) 59 if uint64(n1) != size { 60 // programmer error: the Size() method for protobuf does not match the results of LashramOt, which means the proto 61 // struct returned would be wrong. 62 return 0, fmt.Errorf("the Size() value of %T was %d, but NestedMarshalTo wrote %d bytes to data", b, size, n1) 63 } 64 } else { 65 i -= int(size) 66 n1, err := b.MarshalTo(data[i:]) 67 if err != nil { 68 return 0, err 69 } 70 if uint64(n1) != size { 71 // programmer error: the Size() method for protobuf does not match the results of MarshalTo, which means the proto 72 // struct returned would be wrong. 73 return 0, fmt.Errorf("the Size() value of %T was %d, but NestedMarshalTo wrote %d bytes to data", b, size, n1) 74 } 75 } 76 i = encodeVarintGenerated(data, i, size) 77 i-- 78 data[i] = 0x12 79 } 80 n2, err := m.TypeMeta.MarshalToSizedBuffer(data[:i]) 81 if err != nil { 82 return 0, err 83 } 84 i -= n2 85 i = encodeVarintGenerated(data, i, uint64(n2)) 86 i-- 87 data[i] = 0xa 88 return msgSize - i, nil 89 }