1 /*
2  * Copyright (C) 2016 The Android Open Source Project
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 #include <nvram/messages/message_codec.h>
18 
19 namespace nvram {
20 namespace proto {
21 
MessageEncoderBase(const void * object,const FieldDescriptor * descriptors,size_t num_descriptors)22 MessageEncoderBase::MessageEncoderBase(const void* object,
23                                        const FieldDescriptor* descriptors,
24                                        size_t num_descriptors)
25     : object_(object),
26       descriptors_(descriptors),
27       num_descriptors_(num_descriptors) {}
28 
Encode(const void * object,ProtoWriter * writer,const FieldDescriptor * descriptors,size_t num_descriptors)29 bool MessageEncoderBase::Encode(const void* object,
30                                 ProtoWriter* writer,
31                                 const FieldDescriptor* descriptors,
32                                 size_t num_descriptors) {
33   MessageEncoderBase encoder(object, descriptors, num_descriptors);
34   return encoder.Encode(writer);
35 }
36 
GetSize()37 size_t MessageEncoderBase::GetSize() {
38   CountingOutputStreamBuffer counting_stream;
39   ProtoWriter writer(&counting_stream);
40   return EncodeData(&writer) ? counting_stream.bytes_written() : 0;
41 }
42 
Encode(ProtoWriter * writer)43 bool MessageEncoderBase::Encode(ProtoWriter* writer) {
44   // We need to compute the total size of all struct fields up front in order to
45   // write a length delimiter that designates the end of the encoded nested
46   // message. Note that computing the size of |object| requires a second
47   // |EncodeData()| call in addition to the one that actually encodes the data.
48   // When handling nested message structures, each level triggers its own size
49   // computation, which are redundant with those performed by the levels above.
50   //
51   // For now, we just accept this inefficiency in the interest of keeping things
52   // simple and correct. If this ever becomes a performance problem for deeply
53   // nested structs here are some options:
54   //  * Reserve bytes in |writer| for the encoded size. Once |Encode()|
55   //    completes, it is known how many bytes were required, at which point the
56   //    size field can be updated. The drawback with this solution is that
57   //    varint encoding is variable length, so we'd have to write a degenerated
58   //    varint that may occupy more bytes than actually required.
59   //  * Cache encoded sizes in the struct. This is the solution implemented in
60   //    the regular protobuf implementation. This is relatively straightforward,
61   //    but at the expense of holding data in struct that doesn't really belong
62   //    there.
63   //  * Make a first pass over the struct tree, compute sizes and cache them in
64   //    some auxiliary data structure held in the encoder. This is probably the
65   //    cleanest solution, but comes at the expense of having to thread the size
66   //    cache data structure through the encoding logic.
67   return writer->WriteLengthHeader(GetSize()) && EncodeData(writer);
68 }
69 
EncodeData(ProtoWriter * writer)70 bool MessageEncoderBase::EncodeData(ProtoWriter* writer) {
71   for (size_t i = 0; i < num_descriptors_; ++i) {
72     const FieldDescriptor& desc = descriptors_[i];
73     writer->set_field_number(desc.field_number);
74     if (!desc.encode_function(object_, writer)) {
75       return false;
76     }
77   }
78 
79   return true;
80 }
81 
MessageDecoderBase(void * object,const FieldDescriptor * descriptors,size_t num_descriptors)82 MessageDecoderBase::MessageDecoderBase(void* object,
83                                        const FieldDescriptor* descriptors,
84                                        size_t num_descriptors)
85     : object_(object),
86       descriptors_(descriptors),
87       num_descriptors_(num_descriptors) {}
88 
Decode(void * object,ProtoReader * reader,const FieldDescriptor * descriptors,size_t num_descriptors)89 bool MessageDecoderBase::Decode(void* object,
90                                 ProtoReader* reader,
91                                 const FieldDescriptor* descriptors,
92                                 size_t num_descriptors) {
93   MessageDecoderBase decoder(object, descriptors, num_descriptors);
94   return decoder.Decode(reader);
95 }
96 
Decode(ProtoReader * reader)97 bool MessageDecoderBase::Decode(ProtoReader* reader) {
98   NestedInputStreamBuffer nested_stream_buffer(reader->stream_buffer(),
99                                                reader->field_size());
100   ProtoReader nested_reader(&nested_stream_buffer);
101   return DecodeData(&nested_reader) && nested_reader.Done();
102 }
103 
DecodeData(ProtoReader * reader)104 bool MessageDecoderBase::DecodeData(ProtoReader* reader) {
105   while (!reader->Done()) {
106     if (!reader->ReadWireTag()) {
107       return false;
108     }
109     const FieldDescriptor* desc = FindDescriptor(reader);
110     if (desc) {
111       if (!desc->decode_function(object_, reader)) {
112         return false;
113       }
114     } else {
115       // Unknown field number or wire type mismatch. Skip field data.
116       if (!reader->SkipField()) {
117         return false;
118       }
119     }
120   }
121 
122   return true;
123 }
124 
FindDescriptor(ProtoReader * reader) const125 const FieldDescriptor* MessageDecoderBase::FindDescriptor(
126     ProtoReader* reader) const {
127   for (size_t i = 0; i < num_descriptors_; ++i) {
128     const FieldDescriptor& desc = descriptors_[i];
129     if (reader->field_number() == desc.field_number &&
130         reader->wire_type() == desc.wire_type) {
131       return &desc;
132     }
133   }
134   return nullptr;
135 }
136 
137 }  // namespace proto
138 }  // namespace nvram
139