1 // Copyright 2022 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 <array>
17 #include <cstddef>
18
19 #include "pw_span/span.h"
20 #include "pw_status/status.h"
21 #include "pw_stream/memory_stream.h"
22
23 namespace pw::rpc::internal {
24
25 // Encodes a protobuf to a local span named by result from a list of pw_protobuf
26 // struct initializers. Note that the proto namespace is passed, not the name
27 // of the struct --- ie. exclude the "::Message" suffix.
28 //
29 // PW_ENCODE_PB(pw::rpc::TestProto, encoded, .value = 42);
30 //
31 #define PW_ENCODE_PB(proto, result, ...) \
32 _PW_ENCODE_PB_EXPAND(proto, result, __LINE__, __VA_ARGS__)
33
34 #define _PW_ENCODE_PB_EXPAND(proto, result, unique, ...) \
35 _PW_ENCODE_PB_IMPL(proto, result, unique, __VA_ARGS__)
36
37 #define _PW_ENCODE_PB_IMPL(proto, result, unique, ...) \
38 std::array<std::byte, 2 * sizeof(proto::Message)> _pb_buffer_##unique{}; \
39 const span result = \
40 ::pw::rpc::internal::EncodeProtobuf<proto::Message, \
41 proto::MemoryEncoder>( \
42 proto::Message{__VA_ARGS__}, _pb_buffer_##unique)
43
44 template <typename Message, typename MemoryEncoder>
EncodeProtobuf(const Message & message,span<std::byte> buffer)45 span<const std::byte> EncodeProtobuf(const Message& message,
46 span<std::byte> buffer) {
47 MemoryEncoder encoder(buffer);
48 EXPECT_EQ(encoder.Write(message), OkStatus());
49 return buffer.first(encoder.size());
50 }
51
52 // Decodes a protobuf to a pw_protobuf struct named by result. Note that the
53 // proto namespace is passed, not the name of the struct --- ie. exclude the
54 // "::Message" suffix.
55 //
56 // PW_DECODE_PB(pw::rpc::TestProto, decoded, buffer);
57 //
58 #define PW_DECODE_PB(proto, result, buffer) \
59 proto::Message result; \
60 ::pw::rpc::internal::DecodeProtobuf<proto::Message, proto::StreamDecoder>( \
61 buffer, result);
62
63 template <typename Message, typename StreamDecoder>
DecodeProtobuf(span<const std::byte> buffer,Message & message)64 void DecodeProtobuf(span<const std::byte> buffer, Message& message) {
65 stream::MemoryReader reader(buffer);
66 EXPECT_EQ(StreamDecoder(reader).Read(message), OkStatus());
67 }
68
69 } // namespace pw::rpc::internal
70