project_files/frontlib/util/util.c
changeset 7227 1c859f572d72
parent 7224 5143861c83bd
child 7230 240620f46dd7
--- a/project_files/frontlib/util/util.c	Tue Jun 12 11:25:05 2012 +0200
+++ b/project_files/frontlib/util/util.c	Tue Jun 12 21:10:11 2012 +0200
@@ -6,6 +6,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
+#include <ctype.h>
 
 char *flib_asprintf(const char *fmt, ...) {
 	va_list argp;
@@ -68,3 +69,62 @@
 	}
 	return result;
 }
+
+static bool isAsciiAlnum(char c) {
+	return (c>='0' && c<='9') || (c>='a' && c <='z') || (c>='A' && c <='Z');
+}
+
+char *flib_urlencode(const char *inbuf) {
+	if(!inbuf) {
+		return NULL;
+	}
+	size_t insize = strlen(inbuf);
+	if(insize > SIZE_MAX/4) {
+		flib_log_e("String too long in flib_urlencode: %zu bytes.", insize);
+		return NULL;
+	}
+
+	char *outbuf = flib_malloc(insize*3+1);
+	if(!outbuf) {
+		return NULL;
+	}
+
+    size_t inpos = 0, outpos = 0;
+    while(inbuf[inpos]) {
+        if(isAsciiAlnum(inbuf[inpos])) {
+        	outbuf[outpos++] = inbuf[inpos++];
+        } else {
+            if(snprintf(outbuf+outpos, 4, "%%%02X", (unsigned)((uint8_t*)inbuf)[inpos])<0) {
+            	flib_log_e("printf error in flib_urlencode");
+            	free(outbuf);
+            	return NULL;
+            }
+            inpos++;
+            outpos += 3;
+        }
+    }
+    outbuf[outpos] = 0;
+    char *shrunk = realloc(outbuf, outpos+1);
+    return shrunk ? shrunk : outbuf;
+}
+
+char *flib_urldecode(const char *inbuf) {
+	char *outbuf = flib_malloc(strlen(inbuf)+1);
+	if(!outbuf) {
+		return NULL;
+	}
+
+    size_t inpos = 0, outpos = 0;
+    while(inbuf[inpos]) {
+        if(inbuf[inpos] == '%' && isxdigit(inbuf[inpos+1]) && isxdigit(inbuf[inpos+2])) {
+            char temp[3] = {inbuf[inpos+1],inbuf[inpos+2],0};
+            outbuf[outpos++] = strtol(temp, NULL, 16);
+            inpos += 3;
+        } else {
+        	outbuf[outpos++] = inbuf[inpos++];
+        }
+    }
+    outbuf[outpos] = 0;
+    char *shrunk = realloc(outbuf, outpos+1);
+    return shrunk ? shrunk : outbuf;
+}