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 sw_ID_hpp 16 #define sw_ID_hpp 17 18 #include <cstdint> 19 #include <unordered_map> 20 21 namespace sw { 22 23 // SpirvID is a strongly-typed identifier backed by a uint32_t. 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 SpirvID 30 { 31 public: 32 SpirvID() = default; 33 inline SpirvID(uint32_t id); 34 inline bool operator==(const SpirvID<T> &rhs) const; 35 inline bool operator!=(const SpirvID<T> &rhs) const; 36 inline bool operator<(const SpirvID<T> &rhs) const; 37 38 // value returns the numerical value of the identifier. 39 inline uint32_t value() const; 40 41 private: 42 uint32_t id = 0; 43 }; 44 45 template<typename T> SpirvID(uint32_t id)46SpirvID<T>::SpirvID(uint32_t id) 47 : id(id) 48 {} 49 50 template<typename T> operator ==(const SpirvID<T> & rhs) const51bool SpirvID<T>::operator==(const SpirvID<T> &rhs) const 52 { 53 return id == rhs.id; 54 } 55 56 template<typename T> operator !=(const SpirvID<T> & rhs) const57bool SpirvID<T>::operator!=(const SpirvID<T> &rhs) const 58 { 59 return id != rhs.id; 60 } 61 62 template<typename T> operator <(const SpirvID<T> & rhs) const63bool SpirvID<T>::operator<(const SpirvID<T> &rhs) const 64 { 65 return id < rhs.id; 66 } 67 68 template<typename T> value() const69uint32_t SpirvID<T>::value() const 70 { 71 return id; 72 } 73 74 // HandleMap<T> is an unordered map of SpirvID<T> to T. 75 template<typename T> 76 using HandleMap = std::unordered_map<SpirvID<T>, T>; 77 78 } // namespace sw 79 80 namespace std { 81 82 // std::hash implementation for sw::SpirvID<T> 83 template<typename T> 84 struct hash<sw::SpirvID<T> > 85 { operator ()std::hash86 std::size_t operator()(const sw::SpirvID<T> &id) const noexcept 87 { 88 return std::hash<uint32_t>()(id.value()); 89 } 90 }; 91 92 } // namespace std 93 94 #endif // sw_ID_hpp 95