• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_rpc/internal/nanopb_common.h"
16 
17 #include "pb_decode.h"
18 #include "pb_encode.h"
19 
20 namespace pw::rpc::internal {
21 
22 // Nanopb 3 uses pb_field_s and Nanopb 4 uses pb_msgdesc_s for fields. The
23 // Nanopb version macro is difficult to use, so deduce the correct type from the
24 // pb_decode function.
25 template <typename DecodeFunction>
26 struct NanopbTraits;
27 
28 template <typename FieldsType>
29 struct NanopbTraits<bool(pb_istream_t*, FieldsType, void*)> {
30   using Fields = FieldsType;
31 };
32 
33 using Fields = typename NanopbTraits<decltype(pb_decode)>::Fields;
34 
Encode(NanopbMessageDescriptor fields,ByteSpan buffer,const void * proto_struct) const35 StatusWithSize NanopbMethodSerde::Encode(NanopbMessageDescriptor fields,
36                                          ByteSpan buffer,
37                                          const void* proto_struct) const {
38   auto output = pb_ostream_from_buffer(
39       reinterpret_cast<pb_byte_t*>(buffer.data()), buffer.size());
40   if (!pb_encode(&output, static_cast<Fields>(fields), proto_struct)) {
41     return StatusWithSize::Internal();
42   }
43 
44   return StatusWithSize(output.bytes_written);
45 }
46 
Decode(NanopbMessageDescriptor fields,void * proto_struct,ConstByteSpan buffer) const47 bool NanopbMethodSerde::Decode(NanopbMessageDescriptor fields,
48                                void* proto_struct,
49                                ConstByteSpan buffer) const {
50   auto input = pb_istream_from_buffer(
51       reinterpret_cast<const pb_byte_t*>(buffer.data()), buffer.size());
52   return pb_decode(&input, static_cast<Fields>(fields), proto_struct);
53 }
54 
55 }  // namespace pw::rpc::internal
56