| 122 | } |
| 123 | |
| 124 | static void HexEncode(const bytebuf &in, rdcstr &out) |
| 125 | { |
| 126 | const size_t bytesPerLine = 32; |
| 127 | const size_t bytesPerGroup = 4; |
| 128 | |
| 129 | const char digit[] = "0123456789ABCDEF"; |
| 130 | // Reserve rough required size: |
| 131 | // - 3 characters per byte (two for hex, 1 for ascii), |
| 132 | // - 4 characters per line (3x space between hex and ascii, newline) |
| 133 | // - 1 character per group (space) |
| 134 | // - 2 characters for leading/trailing newline |
| 135 | out.reserve(in.size() * 3 + (in.size() / bytesPerLine) * 4 + (in.size() / bytesPerGroup) + 2); |
| 136 | |
| 137 | // leading newline |
| 138 | out = "\n"; |
| 139 | |
| 140 | // accumulate ascii representation for each line |
| 141 | rdcstr ascii; |
| 142 | |
| 143 | size_t i = 0; |
| 144 | for(byte c : in) |
| 145 | { |
| 146 | out.push_back(digit[(c & 0xf0) >> 4]); |
| 147 | out.push_back(digit[(c & 0x0f) >> 0]); |
| 148 | |
| 149 | if(IsXMLPrintable((char)c)) |
| 150 | ascii.push_back((char)c); |
| 151 | else |
| 152 | ascii.push_back('.'); |
| 153 | |
| 154 | i++; |
| 155 | if((i % bytesPerLine) == 0) |
| 156 | { |
| 157 | out += StringFormat::Fmt(" %s\n", ascii.c_str()); |
| 158 | ascii.clear(); |
| 159 | } |
| 160 | else if((i % bytesPerGroup) == 0) |
| 161 | { |
| 162 | out.push_back(' '); |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | // add remaining part of a line, if we didn't end by completing one |
| 167 | size_t lastLineLength = i % bytesPerLine; |
| 168 | if(lastLineLength > 0) |
| 169 | { |
| 170 | for(i = lastLineLength; i < bytesPerLine; i++) |
| 171 | { |
| 172 | // print 2 spaces where there would be characters |
| 173 | out.push_back(' '); |
| 174 | out.push_back(' '); |
| 175 | |
| 176 | // don't print the group space the first time, since it was already printed, but after that |
| 177 | // print the group space |
| 178 | if((i % bytesPerGroup) == 0 && i > lastLineLength) |
| 179 | out.push_back(' '); |
| 180 | } |
| 181 |
no test coverage detected