3 // ----------------------------------------------------------------------------
5 // code from: http://www.geekhideout.com/urlcode.shtml
7 /* Converts a hex character to its integer value */
8 char from_hex(char ch) {
9 return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
12 /* Converts an integer value to its hex character*/
13 char to_hex(char code) {
14 static char hex[] = "0123456789abcdef";
15 return hex[code & 15];
18 /* Returns a url-encoded version of str */
19 /* IMPORTANT: be sure to free() the returned string after use */
20 char *url_encode(char *str) {
23 pbuf = buf = mallocz(strlen(str) * 3 + 1);
26 if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~')
33 *pbuf++ = '%', *pbuf++ = to_hex(*str >> 4), *pbuf++ = to_hex(*str & 15);
44 /* Returns a url-decoded version of str */
45 /* IMPORTANT: be sure to free() the returned string after use */
46 char *url_decode(char *str) {
47 size_t size = strlen(str) + 1;
49 char *buf = mallocz(size);
50 return url_decode_r(buf, str, size);
53 char *url_decode_r(char *to, char *url, size_t size) {
54 char *s = url, // source
55 *d = to, // destination
56 *e = &to[size - 1]; // destination end
59 if(unlikely(*s == '%')) {
60 if(likely(s[1] && s[2])) {
61 *d++ = from_hex(s[1]) << 4 | from_hex(s[2]);
65 else if(unlikely(*s == '+'))