| 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 | } |