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 "System/Debug.hpp" 19 20 #include <cstdint> 21 #include <unordered_map> 22 23 namespace sw { 24 25 // SpirvID is a strongly-typed identifier backed by a uint32_t. 26 // The template parameter T is not actually used by the implementation of 27 // ID; instead it is used to prevent implicit casts between identifiers of 28 // different T types. 29 // IDs are typically used as a map key to value of type T. 30 template<typename T> 31 class SpirvID 32 { 33 public: 34 SpirvID() = default; 35 inline SpirvID(uint32_t id); 36 37 inline bool operator==(const SpirvID<T> &rhs) const; 38 inline bool operator!=(const SpirvID<T> &rhs) const; 39 inline bool operator<(const SpirvID<T> &rhs) const; 40 41 // Returns the numerical value of the identifier. 42 inline uint32_t value() const; 43 44 private: 45 uint32_t id = 0; // Valid ids are in the range "0 < id < Bound". 46 }; 47 48 template<typename T> SpirvID(uint32_t id)49SpirvID<T>::SpirvID(uint32_t id) 50 : id(id) 51 {} 52 53 template<typename T> operator ==(const SpirvID<T> & rhs) const54bool SpirvID<T>::operator==(const SpirvID<T> &rhs) const 55 { 56 return id == rhs.id; 57 } 58 59 template<typename T> operator !=(const SpirvID<T> & rhs) const60bool SpirvID<T>::operator!=(const SpirvID<T> &rhs) const 61 { 62 return id != rhs.id; 63 } 64 65 template<typename T> operator <(const SpirvID<T> & rhs) const66bool SpirvID<T>::operator<(const SpirvID<T> &rhs) const 67 { 68 return id < rhs.id; 69 } 70 71 template<typename T> value() const72uint32_t SpirvID<T>::value() const 73 { 74 // Assert that we don't attempt to use unassigned IDs. 75 // Use if(id != 0) { ... } to avoid invalid code paths. 76 ASSERT(id != 0); 77 78 return id; 79 } 80 81 // HandleMap<T> is an unordered map of SpirvID<T> to T. 82 template<typename T> 83 using HandleMap = std::unordered_map<SpirvID<T>, T>; 84 85 } // namespace sw 86 87 namespace std { 88 89 // std::hash implementation for sw::SpirvID<T> 90 template<typename T> 91 struct hash<sw::SpirvID<T> > 92 { operator ()std::hash93 std::size_t operator()(const sw::SpirvID<T> &id) const noexcept 94 { 95 return std::hash<uint32_t>()(id.value()); 96 } 97 }; 98 99 } // namespace std 100 101 #endif // sw_ID_hpp 102