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