• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 method identifiers.
21 
22 namespace pw::rpc {
23 
24 class MethodId;
25 
26 namespace internal {
27 constexpr MethodId WrapMethodId(uint32_t id);
28 constexpr uint32_t UnwrapMethodId(MethodId id);
29 }  // namespace internal
30 
31 // An identifier for a method.
32 class MethodId {
33  private:
MethodId(uint32_t id)34   constexpr explicit MethodId(uint32_t id) : id_(id) {}
35   friend constexpr MethodId internal::WrapMethodId(uint32_t id);
36   friend constexpr uint32_t internal::UnwrapMethodId(MethodId id);
37   uint32_t id_;
38 };
39 
40 constexpr bool operator==(MethodId lhs, MethodId rhs) {
41   return internal::UnwrapMethodId(lhs) == internal::UnwrapMethodId(rhs);
42 }
43 
44 constexpr bool operator!=(MethodId lhs, MethodId rhs) { return !(lhs == rhs); }
45 
46 // Comparisons are provided to enable sorting by `MethodId`.
47 
48 constexpr bool operator<(MethodId lhs, MethodId rhs) {
49   return internal::UnwrapMethodId(lhs) < internal::UnwrapMethodId(rhs);
50 }
51 
52 constexpr bool operator>(MethodId lhs, MethodId rhs) { return rhs < lhs; }
53 
54 constexpr bool operator<=(MethodId lhs, MethodId rhs) { return !(lhs > rhs); }
55 
56 constexpr bool operator>=(MethodId lhs, MethodId rhs) { return !(lhs < rhs); }
57 
58 namespace internal {
59 
WrapMethodId(uint32_t id)60 constexpr MethodId WrapMethodId(uint32_t id) { return MethodId(id); }
UnwrapMethodId(MethodId id)61 constexpr uint32_t UnwrapMethodId(MethodId id) { return id.id_; }
62 
63 }  // namespace internal
64 }  // namespace pw::rpc
65 
66 namespace std {
67 
68 template <>
69 struct hash<pw::rpc::MethodId> {
70   size_t operator()(const pw::rpc::MethodId& id) const {
71     return hash<uint32_t>{}(::pw::rpc::internal::UnwrapMethodId(id));
72   }
73 };
74 
75 }  // namespace std
76