1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
15 #include "pw_rpc/internal/nanopb_common.h"
17 #include "pb_decode.h"
18 #include "pb_encode.h"
20 namespace pw::rpc::internal {
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>
28 template <typename FieldsType>
29 struct NanopbTraits<bool(pb_istream_t*, FieldsType, void*)> {
30 using Fields = FieldsType;
33 using Fields = typename NanopbTraits<decltype(pb_decode)>::Fields;
35 StatusWithSize NanopbMethodSerde::Encode(NanopbMessageDescriptor fields,
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();
44 return StatusWithSize(output.bytes_written);
47 bool NanopbMethodSerde::Decode(NanopbMessageDescriptor fields,
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);
55 } // namespace pw::rpc::internal