]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/pretty_binary.cc
update ceph source to reef 18.2.0
[ceph.git] / ceph / src / common / pretty_binary.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #include "pretty_binary.h"
5 #include <stdexcept>
6 #include <sstream>
7
8 std::string pretty_binary_string_reverse(const std::string& pretty)
9 {
10 size_t i = 0;
11 auto raise = [&](size_t failpos) {
12 std::ostringstream ss;
13 ss << "invalid char at pos " << failpos << " of " << pretty;
14 throw std::invalid_argument(ss.str());
15 };
16 auto hexdigit = [&](unsigned char c) -> int32_t {
17 if (c >= '0' && c <= '9') return c - '0';
18 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
19 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
20 return -1;
21 };
22 auto require = [&](unsigned char c) {
23 if (i >= pretty.length() || pretty[i] != c) {
24 raise(i);
25 }
26 ++i;
27 };
28 std::string bin;
29 if (pretty.empty())
30 return bin;
31 bin.reserve(pretty.length());
32 bool strmode;
33 switch (pretty[0]) {
34 case '\'':
35 ++i;
36 strmode = true;
37 break;
38 case '0':
39 ++i;
40 require('x');
41 if (i == pretty.length()) {
42 raise(i);
43 }
44 strmode = false;
45 break;
46 default:
47 raise(0);
48 }
49 for (; i < pretty.length();) {
50 if (strmode) {
51 if (pretty[i] == '\'') {
52 if (i + 1 < pretty.length() && pretty[i + 1] == '\'') {
53 bin.push_back('\'');
54 i += 2;
55 } else {
56 ++i;
57 strmode = false;
58 if (i + 1 < pretty.length()) {
59 require('0');
60 require('x');
61 if (i == pretty.length()) {
62 raise(i);
63 }
64 }
65 }
66 } else {
67 bin.push_back(pretty[i]);
68 ++i;
69 }
70 } else {
71 if (pretty[i] != '\'') {
72 int32_t hex0 = hexdigit(pretty[i]);
73 if (hex0 < 0) {
74 raise(i);
75 }
76 ++i;
77 if (i >= pretty.length()) {
78 raise(i);
79 }
80 int32_t hex1 = hexdigit(pretty[i]);
81 if (hex1 < 0) {
82 raise(i);
83 }
84 bin.push_back(hex0 * 0x10 + hex1);
85 ++i;
86 } else {
87 strmode = true;
88 ++i;
89 }
90 }
91 }
92 if (strmode)
93 raise(i);
94 return bin;
95 }