GMLscripts.com

Discuss and collaborate on GML scripts
Invert

You are not logged in.

#1 2013-10-01 08:14:30

xot
Administrator
Registered: 2007-08-18
Posts: 1,240

url_encode & url_decode

Nocture just posted a url_encode() script on the YoYo Games site that makes my head hurt. It is meant to convert certain characters in a string into percent-encoded octets for inclusion in URLs. Useful if you want to query a web server with a GET request. But the script offends. And while the link to the GMC topic it came from contains a nicer version by Yourself, it is buggy. The cherry on top is that the standard it conforms to, RFC 1738, is out of date.

Here is my scarcely tested crack at RFC 3986 encoding and decoding.

Expand//  url_encode(str)
//	returns a string URL-encoded according to RFC 3986
{
    var str,out,len,hex,safe,i,c,n;
    str = argument0;
    out = "";
    len = string_length(str);
    hex = "0123456789ABCDEF";
    safe = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";
    for (i=1; i<=len; i+=1) 
    {
    	c = string_char_at(str, i);
    	if (not string_pos(c, safe))
    	{
    		n = ord(c);
    		c = "%" + string_char_at(hex, n div 16 + 1) + string_char_at(hex, n mod 16 + 1);
    	}
    	out += c;
    }
    return out;
}
Expand//  url_decode(str)
//	returns a string URL-decoded according to RFC 3986
{
    var str,out,len,hex,i,c,hi,lo;
    str = argument0;
    out = "";
    len = string_length(str);
    hex = "0123456789ABCDEF";
    for (i=1; i<=len; i+=1)
    {
        c = string_char_at(str,i);
        if (c == "%")
        {
            hi = string_pos(string_upper(string_char_at(str,i+1)),hex);
            lo = string_pos(string_upper(string_char_at(str,i+2)),hex);
            if (hi && lo) {
                c = chr(hi-1 << 4 | lo-1);
                i += 2;
            }
        }
        out += c;
    }
    return out;
}

Abusing forum power since 1986.

Offline

Board footer

Powered by FluxBB