Debian Codegraph @

ext/erb/escape/escape.c

raw
1 #include "ruby.h"
2 #include "ruby/encoding.h"
3
4 static VALUE rb_cERB, rb_mEscape, rb_cCGI;
5 static ID id_escapeHTML;
6
7 #define HTML_ESCAPE_MAX_LEN 6
8
9 static const struct {
10 uint8_t len;
11 char str[HTML_ESCAPE_MAX_LEN+1];
12 } html_escape_table[UCHAR_MAX+1] = {
13 #define HTML_ESCAPE(c, str) [c] = {rb_strlen_lit(str), str}
14 HTML_ESCAPE('\'', "'"),
15 HTML_ESCAPE('&', "&"),
16 HTML_ESCAPE('"', """),
17 HTML_ESCAPE('<', "&lt;"),
18 HTML_ESCAPE('>', "&gt;"),
19 #undef HTML_ESCAPE
20 };
21
22 static inline void
23 preserve_original_state(VALUE orig, VALUE dest)
24 {
25 rb_enc_associate(dest, rb_enc_get(orig));
26 }
27
28 static inline long
29 escaped_length(VALUE str)
30 {
31 const long len = RSTRING_LEN(str);
32 if (len >= LONG_MAX / HTML_ESCAPE_MAX_LEN) {
33 ruby_malloc_size_overflow(len, HTML_ESCAPE_MAX_LEN);
34 }
35 return len * HTML_ESCAPE_MAX_LEN;
36 }
37
38 static VALUE
39 optimized_escape_html(VALUE str)
40 {
41 VALUE vbuf;
42 char *buf = ALLOCV_N(char, vbuf, escaped_length(str));
43 const char *cstr = RSTRING_PTR(str);
44 const char *end = cstr + RSTRING_LEN(str);
45
46 char *dest = buf;
47 while (cstr < end) {
48 const unsigned char c = *cstr++;
49 uint8_t len = html_escape_table[c].len;
50 if (len) {
51 memcpy(dest, html_escape_table[c].str, len);
52 dest += len;
53 }
54 else {
55 *dest++ = c;
56 }
57 }
58
59 VALUE escaped = str;
60 if (RSTRING_LEN(str) < (dest - buf)) {
61 escaped = rb_str_new(buf, dest - buf);
62 preserve_original_state(str, escaped);
63 }
64 ALLOCV_END(vbuf);
65 return escaped;
66 }
67
68 // ERB::Util.html_escape is different from CGI.escapeHTML in the following two parts:
69 // * ERB::Util.html_escape converts an argument with #to_s first (only if it's not T_STRING)
70 // * ERB::Util.html_escape does not allocate a new string when nothing needs to be escaped
71 static VALUE
72 erb_escape_html(VALUE self, VALUE str)
73 {
74 if (!RB_TYPE_P(str, T_STRING)) {
75 str = rb_convert_type(str, T_STRING, "String", "to_s");
76 }
77
78 if (rb_enc_str_asciicompat_p(str)) {
79 return optimized_escape_html(str);
80 }
81 else {
82 return rb_funcall(rb_cCGI, id_escapeHTML, 1, str);
83 }
84 }
85
86 void
87 Init_escape(void)
88 {
89 rb_cERB = rb_define_class("ERB", rb_cObject);
90 rb_mEscape = rb_define_module_under(rb_cERB, "Escape");
91 rb_define_module_function(rb_mEscape, "html_escape", erb_escape_html, 1);
92
93 rb_cCGI = rb_define_class("CGI", rb_cObject);
94 id_escapeHTML = rb_intern("escapeHTML");
95 }