shithub: webbox

ref: e51d22809fbc731435eeb935cdaa6d1d8c0b2bff
dir: /urldecode.c/

View raw version
#include <u.h>
#include <libc.h>
#include <bio.h>

char
lookup(char c)
{
	if (c >= '0' && c <= '9')
		return c - '0';
	
	switch (c) {
		case 'a':
		case 'A':
			return 0x0a;
		case 'b':
		case 'B':
			return 0x0b;
		case 'c':
		case 'C':
			return 0x0c;
		case 'd':
		case 'D':
			return 0x0d;
		case 'e':
		case 'E':
			return 0x0e;
		case 'f':
		case 'F':
			return 0x0f;
	}
	fprint(2, "error\n");
	return 0;
}

char
interpret(char a, char b)
{
	return (lookup(a) << 4) | lookup(b);
}

void
printdec(char *s)
{
	char *o, *i, *j;
	int n = strlen(s);
	
	o = mallocz(n+1, 1);
	if (!o)
		sysfatal("%r");
	
	for (i = s, j = o; *i; i++, j++) {
		if (*i == '+') {
			*j = ' ';
			continue;
		}
		if (*i != '%') {
			*j = *i;
			continue;
		}
		*j = interpret(*(++i), *(++i));
	}
	
	print("%s", o);
	free(o);
}

void
main(int argc, char **argv)
{
	Biobuf *b;
	char *s;
	USED(argc, argv);
	
	b = Bfdopen(0, OREAD);
	if (!b)
		sysfatal("%r");
	
	while (s = Brdstr(b, '\n', 1)) {
		printdec(s);
	}
}