escape.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "escape.h"
  2. #include <util/generic/array_size.h>
  3. #include <util/generic/strbuf.h>
  4. namespace NHtml {
  5. namespace {
  6. struct TReplace {
  7. char Char;
  8. bool ForText;
  9. TStringBuf Entity;
  10. };
  11. TReplace Escapable[] = {
  12. {'"', false, TStringBuf("&quot;")},
  13. {'&', true, TStringBuf("&amp;")},
  14. {'<', true, TStringBuf("&lt;")},
  15. {'>', true, TStringBuf("&gt;")},
  16. };
  17. TString EscapeImpl(const TString& value, bool isText) {
  18. auto ci = value.begin();
  19. // Looking for escapable characters.
  20. for (; ci != value.end(); ++ci) {
  21. for (size_t i = (isText ? 1 : 0); i < Y_ARRAY_SIZE(Escapable); ++i) {
  22. if (*ci == Escapable[i].Char) {
  23. goto escape;
  24. }
  25. }
  26. }
  27. // There is no escapable characters, so return original value.
  28. return value;
  29. escape:
  30. TString tmp = TString(value.begin(), ci);
  31. for (; ci != value.end(); ++ci) {
  32. size_t i = (isText ? 1 : 0);
  33. for (; i < Y_ARRAY_SIZE(Escapable); ++i) {
  34. if (*ci == Escapable[i].Char) {
  35. tmp += Escapable[i].Entity;
  36. break;
  37. }
  38. }
  39. if (i == Y_ARRAY_SIZE(Escapable)) {
  40. tmp += *ci;
  41. }
  42. }
  43. return tmp;
  44. }
  45. }
  46. TString EscapeAttributeValue(const TString& value) {
  47. return EscapeImpl(value, false);
  48. }
  49. TString EscapeText(const TString& value) {
  50. return EscapeImpl(value, true);
  51. }
  52. }