Skip to content

Commit

Permalink
HEX-encode only non-printable characters
Browse files Browse the repository at this point in the history
  • Loading branch information
mikhainin committed Jul 14, 2023
1 parent e96e1a6 commit 7676ac3
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/google/protobuf/compiler/php/php_generator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -570,14 +570,24 @@ std::string BinaryToPhpString(const std::string& src) {
'C', 'D', 'E', 'F',
};

dest.resize(src.size() * 4);
char* append_ptr = &dest[0];
dest.reserve(src.size() * 1.2);

for (i = 0; i < src.size(); i++) {
*append_ptr++ = '\\';
*append_ptr++ = 'x';
*append_ptr++ = symbol[(src[i] & 0xf0) >> 4];
*append_ptr++ = symbol[src[i] & 0x0f];
// To escape:
// - escape sequences
// - variable expansion: "hello $username";
// - string termination
if (src[i] == '\\' || src[i] == '$' || src[i] == '"') {
dest += '\\';
dest += src[i];
} else if (std::isprint(src[i])) {
dest += src[i];
} else {
dest += '\\';
dest += 'x';
dest += symbol[(src[i] & 0xf0) >> 4];
dest += symbol[src[i] & 0x0f];
}
}

return dest;
Expand Down

0 comments on commit 7676ac3

Please sign in to comment.