Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 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 | // NestedMarshalTo allows a caller to avoid extra allocations during serialization of an Unknown |
| 28 | // that will contain an object that implements ProtobufMarshaller. |
| 29 | func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64) (int, error) { |
| 30 | var i int |
| 31 | _ = i |
| 32 | var l int |
| 33 | _ = l |
| 34 | data[i] = 0xa |
| 35 | i++ |
| 36 | i = encodeVarintGenerated(data, i, uint64(m.TypeMeta.Size())) |
| 37 | n1, err := m.TypeMeta.MarshalTo(data[i:]) |
| 38 | if err != nil { |
| 39 | return 0, err |
| 40 | } |
| 41 | i += n1 |
| 42 | |
| 43 | if b != nil { |
| 44 | data[i] = 0x12 |
| 45 | i++ |
| 46 | i = encodeVarintGenerated(data, i, size) |
| 47 | n2, err := b.MarshalTo(data[i:]) |
| 48 | if err != nil { |
| 49 | return 0, err |
| 50 | } |
| 51 | if uint64(n2) != size { |
| 52 | // programmer error: the Size() method for protobuf does not match the results of MarshalTo, which means the proto |
| 53 | // struct returned would be wrong. |
| 54 | return 0, fmt.Errorf("the Size() value of %T was %d, but NestedMarshalTo wrote %d bytes to data", b, size, n2) |
| 55 | } |
| 56 | i += n2 |
| 57 | } |
| 58 | |
| 59 | data[i] = 0x1a |
| 60 | i++ |
| 61 | i = encodeVarintGenerated(data, i, uint64(len(m.ContentEncoding))) |
| 62 | i += copy(data[i:], m.ContentEncoding) |
| 63 | |
| 64 | data[i] = 0x22 |
| 65 | i++ |
| 66 | i = encodeVarintGenerated(data, i, uint64(len(m.ContentType))) |
| 67 | i += copy(data[i:], m.ContentType) |
| 68 | return i, nil |
| 69 | } |