From 9973465c0948919d2336cc3346cb82de6472d4d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20Sch=C3=BCtz?= Date: Sat, 25 Apr 2015 12:14:57 +0200 Subject: [PATCH] urlEncode() should only copy if necessary --- source/vibe/textfilter/urlencode.d | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/source/vibe/textfilter/urlencode.d b/source/vibe/textfilter/urlencode.d index 39bd81d9f1..9cca07f7b8 100644 --- a/source/vibe/textfilter/urlencode.d +++ b/source/vibe/textfilter/urlencode.d @@ -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) @@ -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]) { @@ -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]) {