• 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 #pragma once
15 
16 #include "pw_bytes/span.h"
17 #include "pw_status/status_with_size.h"
18 
19 namespace pw::rpc::internal {
20 
21 // Use a void* to cover both Nanopb 3's pb_field_s and Nanopb 4's pb_msgdesc_s.
22 using NanopbMessageDescriptor = const void*;
23 
24 // Serializer/deserializer for nanopb message request and response structs in an
25 // RPC method.
26 class NanopbMethodSerde {
27  public:
NanopbMethodSerde(NanopbMessageDescriptor request_fields,NanopbMessageDescriptor response_fields)28   constexpr NanopbMethodSerde(NanopbMessageDescriptor request_fields,
29                               NanopbMessageDescriptor response_fields)
30       : request_fields_(request_fields), response_fields_(response_fields) {}
31 
EncodeRequest(ByteSpan buffer,const void * proto_struct)32   StatusWithSize EncodeRequest(ByteSpan buffer,
33                                const void* proto_struct) const {
34     return Encode(request_fields_, buffer, proto_struct);
35   }
EncodeResponse(ByteSpan buffer,const void * proto_struct)36   StatusWithSize EncodeResponse(ByteSpan buffer,
37                                 const void* proto_struct) const {
38     return Encode(response_fields_, buffer, proto_struct);
39   }
40 
DecodeRequest(void * proto_struct,ConstByteSpan buffer)41   bool DecodeRequest(void* proto_struct, ConstByteSpan buffer) const {
42     return Decode(request_fields_, proto_struct, buffer);
43   }
DecodeResponse(void * proto_struct,ConstByteSpan buffer)44   bool DecodeResponse(void* proto_struct, ConstByteSpan buffer) const {
45     return Decode(response_fields_, proto_struct, buffer);
46   }
47 
48  private:
49   // Encodes a nanopb protobuf struct to serialized wire format.
50   StatusWithSize Encode(NanopbMessageDescriptor fields,
51                         ByteSpan buffer,
52                         const void* proto_struct) const;
53 
54   // Decodes a serialized protobuf to a nanopb struct.
55   bool Decode(NanopbMessageDescriptor fields,
56               void* proto_struct,
57               ConstByteSpan buffer) const;
58 
59   NanopbMessageDescriptor request_fields_;
60   NanopbMessageDescriptor response_fields_;
61 };
62 
63 }  // namespace pw::rpc::internal
64