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