]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/pretty_binary.h
update source to Ceph Pacific 16.2.2
[ceph.git] / ceph / src / common / pretty_binary.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #pragma once
5
6 #include <string>
7
8 template<typename S>
9 static std::string pretty_binary_string(const S& bin)
10 {
11 std::string pretty;
12 if (bin.empty())
13 return pretty;
14 pretty.reserve(bin.length() * 3);
15 auto printable = [](unsigned char c) -> bool {
16 return (c >= 32) && (c <= 126);
17 };
18 auto append_hex = [&](unsigned char c) {
19 static const char hex[16] = {'0', '1', '2', '3',
20 '4', '5', '6', '7',
21 '8', '9', 'A', 'B',
22 'C', 'D', 'E', 'F'};
23 pretty.push_back(hex[c / 16]);
24 pretty.push_back(hex[c % 16]);
25 };
26 // prologue
27 bool strmode = printable(bin[0]);
28 if (strmode) {
29 pretty.push_back('\'');
30 } else {
31 pretty.push_back('0');
32 pretty.push_back('x');
33 }
34 for (size_t i = 0; i < bin.length(); ++i) {
35 // change mode from hex to str if following 3 characters are printable
36 if (strmode) {
37 if (!printable(bin[i])) {
38 pretty.push_back('\'');
39 pretty.push_back('0');
40 pretty.push_back('x');
41 strmode = false;
42 }
43 } else {
44 if (i + 2 < bin.length() &&
45 printable(bin[i]) &&
46 printable(bin[i + 1]) &&
47 printable(bin[i + 2])) {
48 pretty.push_back('\'');
49 strmode = true;
50 }
51 }
52 if (strmode) {
53 if (bin[i] == '\'')
54 pretty.push_back('\'');
55 pretty.push_back(bin[i]);
56 } else {
57 append_hex(bin[i]);
58 }
59 }
60 // epilog
61 if (strmode) {
62 pretty.push_back('\'');
63 }
64 return pretty;
65 }
66
67 std::string pretty_binary_string_reverse(const std::string& pretty);