Skip to content

Commit

Permalink
urlEncode() should only copy if necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
schuetzm committed May 1, 2015
1 parent ac6d4ff commit 9973465
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions source/vibe/textfilter/urlencode.d
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,34 @@ import std.format;
*/
string urlEncode(string str, string allowed_chars = null)
@safe {
foreach(ubyte c; str) {
switch(c) {
case '-':
case '.':
case '0': .. case '9':
case 'A': .. case 'Z':
case '_':
case 'a': .. case 'z':
case '~':
break;
default:
goto needsEncoding;
}
}
return str;

needsEncoding:
auto dst = appender!string();
dst.reserve(str.length);
filterURLEncode(dst, str, allowed_chars);
return dst.data;
}

unittest {
string s = "hello-world";
assert(s.urlEncode().ptr == s.ptr);
}

/** Returns the decoded version of a given URL encoded string.
*/
string urlDecode(string str)
Expand Down Expand Up @@ -69,7 +91,7 @@ string formDecode(string str)

/** Writes the URL encoded version of the given string to an output range.
*/
void filterURLEncode(R)(ref R dst, string str, string allowed_chars = null, bool form_encoding = false)
void filterURLEncode(R)(ref R dst, string str, string allowed_chars = null, bool form_encoding = false)
{
while( str.length > 0 ) {
switch(str[0]) {
Expand All @@ -96,7 +118,7 @@ void filterURLEncode(R)(ref R dst, string str, string allowed_chars = null, bool

/** Writes the decoded version of the given URL encoded string to an output range.
*/
void filterURLDecode(R)(ref R dst, string str, bool form_encoding = false)
void filterURLDecode(R)(ref R dst, string str, bool form_encoding = false)
{
while( str.length > 0 ) {
switch(str[0]) {
Expand Down

0 comments on commit 9973465

Please sign in to comment.