xref: /aosp_15_r20/external/pigweed/pw_rpc/public/pw_rpc/service_id.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 <cstdint>
17 #include <functional>
18 
19 // NOTE: These wrappers exist in order to provide future compatibility for
20 // different internal representations of service and method identifiers.
21 
22 namespace pw::rpc {
23 
24 class ServiceId;
25 
26 namespace internal {
27 constexpr ServiceId WrapServiceId(uint32_t id);
28 constexpr uint32_t UnwrapServiceId(ServiceId id);
29 }  // namespace internal
30 
31 // An identifier for a service.
32 //
33 // Note: this does not identify instances of a service (Servers), only the
34 // service itself.
35 class ServiceId {
36  private:
ServiceId(uint32_t id)37   constexpr explicit ServiceId(uint32_t id) : id_(id) {}
38   friend constexpr ServiceId internal::WrapServiceId(uint32_t id);
39   friend constexpr uint32_t internal::UnwrapServiceId(ServiceId id);
40   uint32_t id_;
41 };
42 
43 constexpr bool operator==(ServiceId lhs, ServiceId rhs) {
44   return internal::UnwrapServiceId(lhs) == internal::UnwrapServiceId(rhs);
45 }
46 
47 constexpr bool operator!=(ServiceId lhs, ServiceId rhs) {
48   return !(lhs == rhs);
49 }
50 
51 // Comparisons are provided to enable sorting by `ServiceId`.
52 
53 constexpr bool operator<(ServiceId lhs, ServiceId rhs) {
54   return internal::UnwrapServiceId(lhs) < internal::UnwrapServiceId(rhs);
55 }
56 
57 constexpr bool operator>(ServiceId lhs, ServiceId rhs) { return rhs < lhs; }
58 
59 constexpr bool operator<=(ServiceId lhs, ServiceId rhs) { return !(lhs > rhs); }
60 
61 constexpr bool operator>=(ServiceId lhs, ServiceId rhs) { return !(lhs < rhs); }
62 
63 namespace internal {
64 
WrapServiceId(uint32_t id)65 constexpr ServiceId WrapServiceId(uint32_t id) { return ServiceId(id); }
UnwrapServiceId(ServiceId id)66 constexpr uint32_t UnwrapServiceId(ServiceId id) { return id.id_; }
67 
68 }  // namespace internal
69 }  // namespace pw::rpc
70 
71 namespace std {
72 
73 template <>
74 struct hash<pw::rpc::ServiceId> {
75   size_t operator()(const pw::rpc::ServiceId& id) const {
76     return hash<uint32_t>{}(::pw::rpc::internal::UnwrapServiceId(id));
77   }
78 };
79 
80 }  // namespace std
81