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_rpc/internal/method_union.h"
18 #include "pw_rpc/internal/nanopb_method.h"
19 #include "pw_rpc/internal/raw_method_union.h"
20
21 namespace pw::rpc::internal {
22
23 // Method union which holds either a nanopb or a raw method.
24 class NanopbMethodUnion : public MethodUnion {
25 public:
NanopbMethodUnion(RawMethod && method)26 constexpr NanopbMethodUnion(RawMethod&& method)
27 : impl_({.raw = std::move(method)}) {}
NanopbMethodUnion(NanopbMethod && method)28 constexpr NanopbMethodUnion(NanopbMethod&& method)
29 : impl_({.nanopb = std::move(method)}) {}
30
method()31 constexpr const Method& method() const { return impl_.method; }
raw_method()32 constexpr const RawMethod& raw_method() const { return impl_.raw; }
nanopb_method()33 constexpr const NanopbMethod& nanopb_method() const { return impl_.nanopb; }
34
35 private:
36 union {
37 Method method;
38 RawMethod raw;
39 NanopbMethod nanopb;
40 } impl_;
41 };
42
43 // Returns either a raw or nanopb method object, depending on the implemented
44 // function's signature.
45 template <auto method, MethodType type, typename Request, typename Response>
GetNanopbOrRawMethodFor(uint32_t id,NanopbMessageDescriptor request_fields,NanopbMessageDescriptor response_fields)46 constexpr auto GetNanopbOrRawMethodFor(
47 uint32_t id,
48 [[maybe_unused]] NanopbMessageDescriptor request_fields,
49 [[maybe_unused]] NanopbMessageDescriptor response_fields) {
50 if constexpr (RawMethod::matches<method>()) {
51 return GetMethodFor<method, RawMethod, type>(id);
52 } else if constexpr (NanopbMethod::matches<method, Request, Response>()) {
53 return GetMethodFor<method, NanopbMethod, type>(
54 id, request_fields, response_fields);
55 } else {
56 return InvalidMethod<method, type, RawMethod>(id);
57 }
58 };
59
60 } // namespace pw::rpc::internal
61