Module: IDN::Punycode
- Defined in:
- ext/punycode.c
Class Method Summary collapse
-
.IDN::Punycode.decode(string) ⇒ String
Converts Punycode to a string in UTF-8 format.
-
.IDN::Punycode.encode(string) ⇒ String
Converts a string in UTF-8 format to Punycode.
Class Method Details
.IDN::Punycode.decode(string) ⇒ String
Converts Punycode to a string in UTF-8 format.
Raises IDN::Punycode::PunycodeError on failure.
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'ext/punycode.c', line 109
static VALUE decode(VALUE self, VALUE str)
{
int rc;
punycode_uint *ustr;
size_t len;
char *buf = NULL;
VALUE retv;
str = rb_check_convert_type(str, T_STRING, "String", "to_s");
len = RSTRING(str)->len;
ustr = malloc(len * sizeof(punycode_uint));
if (ustr == NULL) {
rb_raise(rb_eNoMemError, "cannot allocate memory (%d bytes)", len);
return Qnil;
}
rc = punycode_decode(RSTRING(str)->len, RSTRING(str)->ptr,
&len, ustr, NULL);
if (rc != PUNYCODE_SUCCESS) {
xfree(ustr);
rb_raise(ePunycodeError, "%s (%d)", punycode_strerror(rc), rc);
return Qnil;
}
buf = stringprep_ucs4_to_utf8(ustr, len, NULL, &len);
retv = rb_str_new(buf, len);
xfree(ustr);
xfree(buf);
return retv;
}
|
.IDN::Punycode.encode(string) ⇒ String
Converts a string in UTF-8 format to Punycode.
Raises IDN::Punycode::PunycodeError on failure.
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'ext/punycode.c', line 59
static VALUE encode(VALUE self, VALUE str)
{
int rc;
punycode_uint *ustr;
size_t len;
size_t buflen = 0x100;
char *buf = NULL;
VALUE retv;
str = rb_check_convert_type(str, T_STRING, "String", "to_s");
ustr = stringprep_utf8_to_ucs4(RSTRING(str)->ptr, RSTRING(str)->len, &len);
while (1) {
buf = realloc(buf, buflen);
if (buf == NULL) {
xfree(ustr);
rb_raise(rb_eNoMemError, "cannot allocate memory (%d bytes)", buflen);
return Qnil;
}
rc = punycode_encode(len, ustr, NULL, &buflen, buf);
if (rc == PUNYCODE_SUCCESS) {
break;
} else if (rc == PUNYCODE_BIG_OUTPUT) {
buflen += 0x100;
} else {
xfree(ustr);
xfree(buf);
rb_raise(ePunycodeError, "%s (%d)", punycode_strerror(rc), rc);
return Qnil;
}
}
retv = rb_str_new(buf, buflen);
xfree(ustr);
xfree(buf);
return retv;
}
|