bin_to_hex.h 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. //
  2. // Copyright(c) 2015 Gabi Melman.
  3. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  4. //
  5. #pragma once
  6. #include <cctype>
  7. #include <spdlog/common.h>
  8. #if defined(__has_include)
  9. # if __has_include(<version>)
  10. # include <version>
  11. # endif
  12. #endif
  13. #if __cpp_lib_span >= 202002L
  14. # include <span>
  15. #endif
  16. //
  17. // Support for logging binary data as hex
  18. // format flags, any combination of the following:
  19. // {:X} - print in uppercase.
  20. // {:s} - don't separate each byte with space.
  21. // {:p} - don't print the position on each line start.
  22. // {:n} - don't split the output to lines.
  23. // {:a} - show ASCII if :n is not set
  24. //
  25. // Examples:
  26. //
  27. // std::vector<char> v(200, 0x0b);
  28. // logger->info("Some buffer {}", spdlog::to_hex(v));
  29. // char buf[128];
  30. // logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf)));
  31. // logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf), 16));
  32. namespace spdlog {
  33. namespace details {
  34. template<typename It>
  35. class dump_info
  36. {
  37. public:
  38. dump_info(It range_begin, It range_end, size_t size_per_line)
  39. : begin_(range_begin)
  40. , end_(range_end)
  41. , size_per_line_(size_per_line)
  42. {}
  43. // do not use begin() and end() to avoid collision with fmt/ranges
  44. It get_begin() const
  45. {
  46. return begin_;
  47. }
  48. It get_end() const
  49. {
  50. return end_;
  51. }
  52. size_t size_per_line() const
  53. {
  54. return size_per_line_;
  55. }
  56. private:
  57. It begin_, end_;
  58. size_t size_per_line_;
  59. };
  60. } // namespace details
  61. // create a dump_info that wraps the given container
  62. template<typename Container>
  63. inline details::dump_info<typename Container::const_iterator> to_hex(const Container &container, size_t size_per_line = 32)
  64. {
  65. static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
  66. using Iter = typename Container::const_iterator;
  67. return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
  68. }
  69. #if __cpp_lib_span >= 202002L
  70. template<typename Value, size_t Extent>
  71. inline details::dump_info<typename std::span<Value, Extent>::iterator> to_hex(
  72. const std::span<Value, Extent> &container, size_t size_per_line = 32)
  73. {
  74. using Container = std::span<Value, Extent>;
  75. static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
  76. using Iter = typename Container::iterator;
  77. return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
  78. }
  79. #endif
  80. // create dump_info from ranges
  81. template<typename It>
  82. inline details::dump_info<It> to_hex(const It range_begin, const It range_end, size_t size_per_line = 32)
  83. {
  84. return details::dump_info<It>(range_begin, range_end, size_per_line);
  85. }
  86. } // namespace spdlog
  87. namespace
  88. #ifdef SPDLOG_USE_STD_FORMAT
  89. std
  90. #else
  91. fmt
  92. #endif
  93. {
  94. template<typename T>
  95. struct formatter<spdlog::details::dump_info<T>, char>
  96. {
  97. const char delimiter = ' ';
  98. bool put_newlines = true;
  99. bool put_delimiters = true;
  100. bool use_uppercase = false;
  101. bool put_positions = true; // position on start of each line
  102. bool show_ascii = false;
  103. // parse the format string flags
  104. template<typename ParseContext>
  105. SPDLOG_CONSTEXPR_FUNC auto parse(ParseContext &ctx) -> decltype(ctx.begin())
  106. {
  107. auto it = ctx.begin();
  108. while (it != ctx.end() && *it != '}')
  109. {
  110. switch (*it)
  111. {
  112. case 'X':
  113. use_uppercase = true;
  114. break;
  115. case 's':
  116. put_delimiters = false;
  117. break;
  118. case 'p':
  119. put_positions = false;
  120. break;
  121. case 'n':
  122. put_newlines = false;
  123. show_ascii = false;
  124. break;
  125. case 'a':
  126. if (put_newlines)
  127. {
  128. show_ascii = true;
  129. }
  130. break;
  131. }
  132. ++it;
  133. }
  134. return it;
  135. }
  136. // format the given bytes range as hex
  137. template<typename FormatContext, typename Container>
  138. auto format(const spdlog::details::dump_info<Container> &the_range, FormatContext &ctx) const -> decltype(ctx.out())
  139. {
  140. SPDLOG_CONSTEXPR const char *hex_upper = "0123456789ABCDEF";
  141. SPDLOG_CONSTEXPR const char *hex_lower = "0123456789abcdef";
  142. const char *hex_chars = use_uppercase ? hex_upper : hex_lower;
  143. #if !defined(SPDLOG_USE_STD_FORMAT) && FMT_VERSION < 60000
  144. auto inserter = ctx.begin();
  145. #else
  146. auto inserter = ctx.out();
  147. #endif
  148. int size_per_line = static_cast<int>(the_range.size_per_line());
  149. auto start_of_line = the_range.get_begin();
  150. for (auto i = the_range.get_begin(); i != the_range.get_end(); i++)
  151. {
  152. auto ch = static_cast<unsigned char>(*i);
  153. if (put_newlines && (i == the_range.get_begin() || i - start_of_line >= size_per_line))
  154. {
  155. if (show_ascii && i != the_range.get_begin())
  156. {
  157. *inserter++ = delimiter;
  158. *inserter++ = delimiter;
  159. for (auto j = start_of_line; j < i; j++)
  160. {
  161. auto pc = static_cast<unsigned char>(*j);
  162. *inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
  163. }
  164. }
  165. put_newline(inserter, static_cast<size_t>(i - the_range.get_begin()));
  166. // put first byte without delimiter in front of it
  167. *inserter++ = hex_chars[(ch >> 4) & 0x0f];
  168. *inserter++ = hex_chars[ch & 0x0f];
  169. start_of_line = i;
  170. continue;
  171. }
  172. if (put_delimiters && i != the_range.get_begin())
  173. {
  174. *inserter++ = delimiter;
  175. }
  176. *inserter++ = hex_chars[(ch >> 4) & 0x0f];
  177. *inserter++ = hex_chars[ch & 0x0f];
  178. }
  179. if (show_ascii) // add ascii to last line
  180. {
  181. if (the_range.get_end() - the_range.get_begin() > size_per_line)
  182. {
  183. auto blank_num = size_per_line - (the_range.get_end() - start_of_line);
  184. while (blank_num-- > 0)
  185. {
  186. *inserter++ = delimiter;
  187. *inserter++ = delimiter;
  188. if (put_delimiters)
  189. {
  190. *inserter++ = delimiter;
  191. }
  192. }
  193. }
  194. *inserter++ = delimiter;
  195. *inserter++ = delimiter;
  196. for (auto j = start_of_line; j != the_range.get_end(); j++)
  197. {
  198. auto pc = static_cast<unsigned char>(*j);
  199. *inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
  200. }
  201. }
  202. return inserter;
  203. }
  204. // put newline(and position header)
  205. template<typename It>
  206. void put_newline(It inserter, std::size_t pos) const
  207. {
  208. #ifdef _WIN32
  209. *inserter++ = '\r';
  210. #endif
  211. *inserter++ = '\n';
  212. if (put_positions)
  213. {
  214. spdlog::fmt_lib::format_to(inserter, SPDLOG_FMT_STRING("{:04X}: "), pos);
  215. }
  216. }
  217. };
  218. } // namespace std