blob: ead96ee055432e5f393bb2449afb0c2044d570d6 [file] [log] [blame]
sslobodrd046be82019-01-16 10:02:22 -05001/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package runtime
18
19import (
20 "fmt"
21)
22
23type 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.
29func (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}