src: Refactor util::hexdump

This commit is contained in:
Tatsuhiro Tsujikawa 2015-03-24 21:43:28 +09:00
parent 89b8039466
commit 94bf8dcd4e
1 changed files with 15 additions and 17 deletions

View File

@ -1046,20 +1046,18 @@ std::string make_hostport(const char *host, uint16_t port) {
return hostport; return hostport;
} }
#define NGHTTP2_SPACES \
" " \
" "
namespace { namespace {
void hexdump8(FILE *out, const uint8_t *first, const uint8_t *last) { void hexdump8(FILE *out, const uint8_t *first, const uint8_t *last) {
auto stop = std::min(first + 8, last); auto stop = std::min(first + 8, last);
for (auto k = first; k != stop; ++k) { for (auto k = first; k != stop; ++k) {
fprintf(out, "%02x ", *k); fprintf(out, "%02x ", *k);
} }
/* each byte needs 3 spaces (2 hex value and space). we have extra // each byte needs 3 spaces (2 hex value and space)
space after 8 bytes */ for (; stop != first + 8; ++stop) {
fprintf(out, "%.*s", static_cast<int>((first + 8 - stop) * 3 + 1), fputs(" ", out);
NGHTTP2_SPACES); }
// we have extra space after 8 bytes
fputc(' ', out);
} }
} // namespace } // namespace
@ -1076,11 +1074,11 @@ void hexdump(FILE *out, const uint8_t *src, size_t len) {
auto nextlen = std::min(static_cast<ptrdiff_t>(16), end - i); auto nextlen = std::min(static_cast<ptrdiff_t>(16), end - i);
if (nextlen == buflen && if (nextlen == buflen &&
std::equal(std::begin(buf), std::begin(buf) + buflen, i)) { std::equal(std::begin(buf), std::begin(buf) + buflen, i)) {
/* as long as adjacent 16 bytes block are the same, we just // as long as adjacent 16 bytes block are the same, we just
print single '*'. */ // print single '*'.
if (!repeated) { if (!repeated) {
repeated = true; repeated = true;
fwrite("*\n", 2, 1, out); fputs("*\n", out);
} }
i += nextlen; i += nextlen;
continue; continue;
@ -1088,25 +1086,25 @@ void hexdump(FILE *out, const uint8_t *src, size_t len) {
repeated = false; repeated = false;
fprintf(out, "%08lx", static_cast<unsigned long>(i - src)); fprintf(out, "%08lx", static_cast<unsigned long>(i - src));
if (i == end) { if (i == end) {
fwrite("\n", 2, 1, out); fputc('\n', out);
break; break;
} }
fwrite(" ", 2, 1, out); fputs(" ", out);
hexdump8(out, i, end); hexdump8(out, i, end);
hexdump8(out, i + 8, std::max(i + 8, end)); hexdump8(out, i + 8, std::max(i + 8, end));
fwrite("|", 1, 1, out); fputc('|', out);
auto stop = std::min(i + 16, end); auto stop = std::min(i + 16, end);
buflen = stop - i; buflen = stop - i;
auto p = buf.data(); auto p = buf.data();
for (; i != stop; ++i) { for (; i != stop; ++i) {
*p++ = *i; *p++ = *i;
if (0x20 <= *i && *i <= 0x7e) { if (0x20 <= *i && *i <= 0x7e) {
fwrite(i, 1, 1, out); fputc(*i, out);
} else { } else {
fwrite(".", 1, 1, out); fputc('.', out);
} }
} }
fwrite("|\n", 2, 1, out); fputs("|\n", out);
} }
} }