1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 2 // -*- mode: C++ -*- 3 // 4 // Copyright 2023-2024 Google LLC 5 // 6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the 7 // "License"); you may not use this file except in compliance with the 8 // License. You may obtain a copy of the License at 9 // 10 // https://llvm.org/LICENSE.txt 11 // 12 // Unless required by applicable law or agreed to in writing, software 13 // distributed under the License is distributed on an "AS IS" BASIS, 14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 // See the License for the specific language governing permissions and 16 // limitations under the License. 17 // 18 // Author: Giuliano Procida 19 20 #ifndef STG_HEX_H_ 21 #define STG_HEX_H_ 22 23 #include <cstddef> // for std::size_t 24 #include <functional> // for std::hash 25 #include <ios> 26 #include <ostream> 27 28 namespace stg { 29 30 template <typename T> 31 struct Hex { HexHex32 explicit Hex(const T& value) : value(value) {} 33 auto operator<=>(const Hex<T>& other) const = default; 34 T value; 35 }; 36 37 template <typename T> Hex(const T&) -> Hex<T>; 38 39 template <typename T> 40 std::ostream& operator<<(std::ostream& os, const Hex<T>& hex_value) { 41 // not quite right if an exception is thrown 42 const auto flags = os.flags(); 43 os << "0x" << std::hex << hex_value.value; 44 os.flags(flags); 45 return os; 46 } 47 48 } // namespace stg 49 50 template <typename T> 51 struct std::hash<stg::Hex<T>> { 52 std::size_t operator()(const stg::Hex<T>& hex) const noexcept { 53 return std::hash<T>{}(hex.value); 54 } 55 }; 56 57 #endif // STG_HEX_H_ 58