string_transform.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "string_transform.h"
  2. #include <google/protobuf/stubs/strutil.h>
  3. #include <library/cpp/string_utils/base64/base64.h>
  4. namespace NProtobufJson {
  5. void TCEscapeTransform::Transform(TString& str) const {
  6. str = google::protobuf::CEscape(str);
  7. }
  8. void TSafeUtf8CEscapeTransform::Transform(TString& str) const {
  9. str = google::protobuf::strings::Utf8SafeCEscape(str);
  10. }
  11. void TDoubleEscapeTransform::Transform(TString& str) const {
  12. TString escaped = google::protobuf::CEscape(str);
  13. str = "";
  14. for (char* it = escaped.begin(); *it; ++it) {
  15. if (*it == '\\' || *it == '\"')
  16. str += "\\";
  17. str += *it;
  18. }
  19. }
  20. void TDoubleUnescapeTransform::Transform(TString& str) const {
  21. str = google::protobuf::UnescapeCEscapeString(Unescape(str));
  22. }
  23. TString TDoubleUnescapeTransform::Unescape(const TString& str) const {
  24. if (str.empty()) {
  25. return str;
  26. }
  27. TString result;
  28. result.reserve(str.size());
  29. char prev = str[0];
  30. bool doneOutput = true;
  31. for (const char* it = str.c_str() + 1; *it; ++it) {
  32. if (doneOutput && prev == '\\' && (*it == '\\' || *it == '\"')) {
  33. doneOutput = false;
  34. } else {
  35. result += prev;
  36. doneOutput = true;
  37. }
  38. prev = *it;
  39. }
  40. if ((doneOutput && prev != '\\') || !doneOutput) {
  41. result += prev;
  42. }
  43. return result;
  44. }
  45. void TBase64EncodeBytesTransform::TransformBytes(TString &str) const {
  46. str = Base64Encode(str);
  47. }
  48. void TBase64DecodeBytesTransform::TransformBytes(TString &str) const {
  49. str = Base64Decode(str);
  50. }
  51. }