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 #pragma once
15
16 #include "pb_decode.h"
17 #include "pb_encode.h"
18 #include "pw_span/span.h"
19
20 namespace pw::rpc::internal {
21
22 // Encodes a protobuf to a local span named by result from a list of nanopb
23 // struct initializers.
24 //
25 // PW_ENCODE_PB(pw_rpc_TestProto, encoded, .value = 42);
26 //
27 #define PW_ENCODE_PB(proto, result, ...) \
28 _PW_ENCODE_PB_EXPAND(proto, result, __LINE__, __VA_ARGS__)
29
30 #define _PW_ENCODE_PB_EXPAND(proto, result, unique, ...) \
31 _PW_ENCODE_PB_IMPL(proto, result, unique, __VA_ARGS__)
32
33 #define _PW_ENCODE_PB_IMPL(proto, result, unique, ...) \
34 std::array<pb_byte_t, 2 * sizeof(proto)> _pb_buffer_##unique{}; \
35 const span result = \
36 ::pw::rpc::internal::EncodeProtobuf<proto, proto##_fields>( \
37 proto{__VA_ARGS__}, _pb_buffer_##unique)
38
39 template <typename T, auto kFields>
EncodeProtobuf(const T & protobuf,span<pb_byte_t> buffer)40 span<const std::byte> EncodeProtobuf(const T& protobuf,
41 span<pb_byte_t> buffer) {
42 auto output = pb_ostream_from_buffer(buffer.data(), buffer.size());
43 EXPECT_TRUE(pb_encode(&output, kFields, &protobuf));
44 return as_bytes(buffer.first(output.bytes_written));
45 }
46
47 // Decodes a protobuf to a nanopb struct named by result.
48 #define PW_DECODE_PB(proto, result, buffer) \
49 proto result; \
50 ::pw::rpc::internal::DecodeProtobuf<proto, proto##_fields>( \
51 span(reinterpret_cast<const pb_byte_t*>(buffer.data()), buffer.size()), \
52 result);
53
54 template <typename T, auto kFields>
DecodeProtobuf(span<const pb_byte_t> buffer,T & protobuf)55 void DecodeProtobuf(span<const pb_byte_t> buffer, T& protobuf) {
56 auto input = pb_istream_from_buffer(buffer.data(), buffer.size());
57 EXPECT_TRUE(pb_decode(&input, kFields, &protobuf));
58 }
59
60 } // namespace pw::rpc::internal
61