xref: /aosp_15_r20/external/pigweed/pw_rpc/pwpb/public/pw_rpc/pwpb/internal/method_union.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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 "pw_rpc/internal/method_union.h"
17 #include "pw_rpc/pwpb/internal/common.h"
18 #include "pw_rpc/pwpb/internal/method.h"
19 #include "pw_rpc/raw/internal/method_union.h"
20 
21 namespace pw::rpc::internal {
22 
23 // MethodUnion which holds a pw_protobuf method or a raw method.
24 class PwpbMethodUnion : public MethodUnion {
25  public:
PwpbMethodUnion(RawMethod && method)26   constexpr PwpbMethodUnion(RawMethod&& method)
27       : impl_({.raw = std::move(method)}) {}
PwpbMethodUnion(PwpbMethod && method)28   constexpr PwpbMethodUnion(PwpbMethod&& method)
29       : impl_({.pwpb = 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; }
pwpb_method()33   constexpr const PwpbMethod& pwpb_method() const { return impl_.pwpb; }
34 
35  private:
36   union {
37     Method method;
38     RawMethod raw;
39     PwpbMethod pwpb;
40   } impl_;
41 };
42 
43 // Deduces the type of an implemented service method from its signature, and
44 // returns the appropriate MethodUnion object to invoke it.
45 template <auto kMethod, MethodType kType, typename Request, typename Response>
GetPwpbOrRawMethodFor(uint32_t id,const PwpbMethodSerde & serde)46 constexpr auto GetPwpbOrRawMethodFor(uint32_t id,
47                                      const PwpbMethodSerde& serde) {
48   if constexpr (RawMethod::matches<kMethod>()) {
49     return GetMethodFor<kMethod, RawMethod, kType>(id);
50   } else if constexpr (PwpbMethod::matches<kMethod, Request, Response>()) {
51     return GetMethodFor<kMethod, PwpbMethod, kType>(id, serde);
52   } else {
53     return InvalidMethod<kMethod, kType, RawMethod>(id);
54   }
55 }
56 
57 }  // namespace pw::rpc::internal
58