to_hex_array.hpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright Antony Polukhin, 2016-2024.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_STACKTRACE_DETAIL_TO_HEX_ARRAY_HPP
  7. #define BOOST_STACKTRACE_DETAIL_TO_HEX_ARRAY_HPP
  8. #include <boost/config.hpp>
  9. #ifdef BOOST_HAS_PRAGMA_ONCE
  10. # pragma once
  11. #endif
  12. #include <array>
  13. #include <type_traits>
  14. namespace boost { namespace stacktrace { namespace detail {
  15. BOOST_STATIC_CONSTEXPR char to_hex_array_bytes[] = "0123456789ABCDEF";
  16. template <class T>
  17. inline std::array<char, 2 + sizeof(void*) * 2 + 1> to_hex_array(T addr) noexcept {
  18. std::array<char, 2 + sizeof(void*) * 2 + 1> ret = {"0x"};
  19. ret.back() = '\0';
  20. static_assert(!std::is_pointer<T>::value, "");
  21. const std::size_t s = sizeof(T);
  22. char* out = ret.data() + s * 2 + 1;
  23. for (std::size_t i = 0; i < s; ++i) {
  24. const unsigned char tmp_addr = (addr & 0xFFu);
  25. *out = to_hex_array_bytes[tmp_addr & 0xF];
  26. -- out;
  27. *out = to_hex_array_bytes[tmp_addr >> 4];
  28. -- out;
  29. addr >>= 8;
  30. }
  31. return ret;
  32. }
  33. inline std::array<char, 2 + sizeof(void*) * 2 + 1> to_hex_array(const void* addr) noexcept {
  34. return to_hex_array(
  35. reinterpret_cast< std::make_unsigned<std::ptrdiff_t>::type >(addr)
  36. );
  37. }
  38. }}} // namespace boost::stacktrace::detail
  39. #endif // BOOST_STACKTRACE_DETAIL_TO_HEX_ARRAY_HPP