|
| 1 | +#include "ruby.h" |
| 2 | +#include "ruby/encoding.h" |
| 3 | + |
| 4 | +static VALUE rb_cERB, rb_mEscape; |
| 5 | + |
| 6 | +#define HTML_ESCAPE_MAX_LEN 6 |
| 7 | + |
| 8 | +static const struct { |
| 9 | + uint8_t len; |
| 10 | + char str[HTML_ESCAPE_MAX_LEN+1]; |
| 11 | +} html_escape_table[UCHAR_MAX+1] = { |
| 12 | +#define HTML_ESCAPE(c, str) [c] = {rb_strlen_lit(str), str} |
| 13 | + HTML_ESCAPE('\'', "'"), |
| 14 | + HTML_ESCAPE('&', "&"), |
| 15 | + HTML_ESCAPE('"', """), |
| 16 | + HTML_ESCAPE('<', "<"), |
| 17 | + HTML_ESCAPE('>', ">"), |
| 18 | +#undef HTML_ESCAPE |
| 19 | +}; |
| 20 | + |
| 21 | +static inline void |
| 22 | +preserve_original_state(VALUE orig, VALUE dest) |
| 23 | +{ |
| 24 | + rb_enc_associate(dest, rb_enc_get(orig)); |
| 25 | +} |
| 26 | + |
| 27 | +static inline long |
| 28 | +escaped_length(VALUE str) |
| 29 | +{ |
| 30 | + const long len = RSTRING_LEN(str); |
| 31 | + if (len >= LONG_MAX / HTML_ESCAPE_MAX_LEN) { |
| 32 | + ruby_malloc_size_overflow(len, HTML_ESCAPE_MAX_LEN); |
| 33 | + } |
| 34 | + return len * HTML_ESCAPE_MAX_LEN; |
| 35 | +} |
| 36 | + |
| 37 | +static VALUE |
| 38 | +optimized_escape_html(VALUE str) |
| 39 | +{ |
| 40 | + VALUE vbuf; |
| 41 | + char *buf = ALLOCV_N(char, vbuf, escaped_length(str)); |
| 42 | + const char *cstr = RSTRING_PTR(str); |
| 43 | + const char *end = cstr + RSTRING_LEN(str); |
| 44 | + |
| 45 | + char *dest = buf; |
| 46 | + while (cstr < end) { |
| 47 | + const unsigned char c = *cstr++; |
| 48 | + uint8_t len = html_escape_table[c].len; |
| 49 | + if (len) { |
| 50 | + memcpy(dest, html_escape_table[c].str, len); |
| 51 | + dest += len; |
| 52 | + } |
| 53 | + else { |
| 54 | + *dest++ = c; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + VALUE escaped; |
| 59 | + if (RSTRING_LEN(str) < (dest - buf)) { |
| 60 | + escaped = rb_str_new(buf, dest - buf); |
| 61 | + preserve_original_state(str, escaped); |
| 62 | + } |
| 63 | + else { |
| 64 | + escaped = rb_str_dup(str); |
| 65 | + } |
| 66 | + ALLOCV_END(vbuf); |
| 67 | + return escaped; |
| 68 | +} |
| 69 | + |
| 70 | +static VALUE |
| 71 | +cgiesc_escape_html(VALUE self, VALUE str) |
| 72 | +{ |
| 73 | + StringValue(str); |
| 74 | + |
| 75 | + if (rb_enc_str_asciicompat_p(str)) { |
| 76 | + return optimized_escape_html(str); |
| 77 | + } |
| 78 | + else { |
| 79 | + return rb_call_super(1, &str); |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +static VALUE |
| 84 | +erb_escape_html(VALUE self, VALUE str) |
| 85 | +{ |
| 86 | + str = rb_funcall(str, rb_intern("to_s"), 0); |
| 87 | + return cgiesc_escape_html(self, str); |
| 88 | +} |
| 89 | + |
| 90 | +void |
| 91 | +Init_erb(void) |
| 92 | +{ |
| 93 | + rb_cERB = rb_define_class("ERB", rb_cObject); |
| 94 | + rb_mEscape = rb_define_module_under(rb_cERB, "Escape"); |
| 95 | + rb_define_method(rb_mEscape, "html_escape", erb_escape_html, 1); |
| 96 | +} |
0 commit comments