summaryrefslogtreecommitdiffstats
path: root/src/common/pretty_binary.h
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-21 11:54:28 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-21 11:54:28 +0000
commite6918187568dbd01842d8d1d2c808ce16a894239 (patch)
tree64f88b554b444a49f656b6c656111a145cbbaa28 /src/common/pretty_binary.h
parentInitial commit. (diff)
downloadceph-upstream/18.2.2.tar.xz
ceph-upstream/18.2.2.zip
Adding upstream version 18.2.2.upstream/18.2.2
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/common/pretty_binary.h')
-rw-r--r--src/common/pretty_binary.h67
1 files changed, 67 insertions, 0 deletions
diff --git a/src/common/pretty_binary.h b/src/common/pretty_binary.h
new file mode 100644
index 000000000..5f1829747
--- /dev/null
+++ b/src/common/pretty_binary.h
@@ -0,0 +1,67 @@
+// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
+// vim: ts=8 sw=2 smarttab
+
+#pragma once
+
+#include <string>
+
+template<typename S>
+static std::string pretty_binary_string(const S& bin)
+{
+ std::string pretty;
+ if (bin.empty())
+ return pretty;
+ pretty.reserve(bin.length() * 3);
+ auto printable = [](unsigned char c) -> bool {
+ return (c >= 32) && (c <= 126);
+ };
+ auto append_hex = [&](unsigned char c) {
+ static const char hex[16] = {'0', '1', '2', '3',
+ '4', '5', '6', '7',
+ '8', '9', 'A', 'B',
+ 'C', 'D', 'E', 'F'};
+ pretty.push_back(hex[c / 16]);
+ pretty.push_back(hex[c % 16]);
+ };
+ // prologue
+ bool strmode = printable(bin[0]);
+ if (strmode) {
+ pretty.push_back('\'');
+ } else {
+ pretty.push_back('0');
+ pretty.push_back('x');
+ }
+ for (size_t i = 0; i < bin.length(); ++i) {
+ // change mode from hex to str if following 3 characters are printable
+ if (strmode) {
+ if (!printable(bin[i])) {
+ pretty.push_back('\'');
+ pretty.push_back('0');
+ pretty.push_back('x');
+ strmode = false;
+ }
+ } else {
+ if (i + 2 < bin.length() &&
+ printable(bin[i]) &&
+ printable(bin[i + 1]) &&
+ printable(bin[i + 2])) {
+ pretty.push_back('\'');
+ strmode = true;
+ }
+ }
+ if (strmode) {
+ if (bin[i] == '\'')
+ pretty.push_back('\'');
+ pretty.push_back(bin[i]);
+ } else {
+ append_hex(bin[i]);
+ }
+ }
+ // epilog
+ if (strmode) {
+ pretty.push_back('\'');
+ }
+ return pretty;
+}
+
+std::string pretty_binary_string_reverse(const std::string& pretty);