to_hex_array.hpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright Antony Polukhin, 2016-2019.
  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 <boost/array.hpp>
  13. #include <boost/static_assert.hpp>
  14. #include <boost/type_traits/is_pointer.hpp>
  15. #include <boost/type_traits/make_unsigned.hpp>
  16. namespace boost { namespace stacktrace { namespace detail {
  17. BOOST_STATIC_CONSTEXPR char to_hex_array_bytes[] = "0123456789ABCDEF";
  18. template <class T>
  19. inline boost::array<char, 2 + sizeof(void*) * 2 + 1> to_hex_array(T addr) BOOST_NOEXCEPT {
  20. boost::array<char, 2 + sizeof(void*) * 2 + 1> ret = {"0x"};
  21. ret.back() = '\0';
  22. BOOST_STATIC_ASSERT_MSG(!boost::is_pointer<T>::value, "");
  23. const std::size_t s = sizeof(T);
  24. char* out = ret.data() + s * 2 + 1;
  25. for (std::size_t i = 0; i < s; ++i) {
  26. const unsigned char tmp_addr = (addr & 0xFFu);
  27. *out = to_hex_array_bytes[tmp_addr & 0xF];
  28. -- out;
  29. *out = to_hex_array_bytes[tmp_addr >> 4];
  30. -- out;
  31. addr >>= 8;
  32. }
  33. return ret;
  34. }
  35. inline boost::array<char, 2 + sizeof(void*) * 2 + 1> to_hex_array(const void* addr) BOOST_NOEXCEPT {
  36. return to_hex_array(
  37. reinterpret_cast< boost::make_unsigned<std::ptrdiff_t>::type >(addr)
  38. );
  39. }
  40. }}} // namespace boost::stacktrace::detail
  41. #endif // BOOST_STACKTRACE_DETAIL_TO_HEX_ARRAY_HPP