1 // Copyright 2019 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef VK_DEBUG_ID_HPP_
16 #define VK_DEBUG_ID_HPP_
17
18 #include <functional> // std::hash
19
20 namespace vk {
21 namespace dbg {
22
23 // ID is a strongly-typed identifier backed by a int.
24 // The template parameter T is not actually used by the implementation of
25 // ID; instead it is used to prevent implicit casts between identifiers of
26 // different T types.
27 // IDs are typically used as a map key to value of type T.
28 template<typename T>
29 class ID
30 {
31 public:
32 ID() = default;
33
34 inline ID(int id);
35 inline bool operator==(const ID<T> &rhs) const;
36 inline bool operator!=(const ID<T> &rhs) const;
37 inline bool operator<(const ID<T> &rhs) const;
38 inline ID operator++();
39 inline ID operator++(int);
40
41 // value returns the numerical value of the identifier.
42 inline int value() const;
43
44 private:
45 int id = 0;
46 };
47
48 template<typename T>
ID(int id)49 ID<T>::ID(int id)
50 : id(id)
51 {}
52
53 template<typename T>
operator ==(const ID<T> & rhs) const54 bool ID<T>::operator==(const ID<T> &rhs) const
55 {
56 return id == rhs.id;
57 }
58
59 template<typename T>
operator !=(const ID<T> & rhs) const60 bool ID<T>::operator!=(const ID<T> &rhs) const
61 {
62 return id != rhs.id;
63 }
64
65 template<typename T>
operator <(const ID<T> & rhs) const66 bool ID<T>::operator<(const ID<T> &rhs) const
67 {
68 return id < rhs.id;
69 }
70
71 template<typename T>
operator ++()72 ID<T> ID<T>::operator++()
73 {
74 return ID(++id);
75 }
76
77 template<typename T>
operator ++(int)78 ID<T> ID<T>::operator++(int)
79 {
80 return ID(id++);
81 }
82
83 template<typename T>
value() const84 int ID<T>::value() const
85 {
86 return id;
87 }
88
89 } // namespace dbg
90 } // namespace vk
91
92 namespace std {
93
94 // std::hash implementation for vk::dbg::ID<T>
95 template<typename T>
96 struct hash<vk::dbg::ID<T> >
97 {
operator ()std::hash98 std::size_t operator()(const vk::dbg::ID<T> &id) const noexcept
99 {
100 return std::hash<int>()(id.value());
101 }
102 };
103
104 } // namespace std
105
106 #endif // VK_DEBUG_ID_HPP_
107