summaryrefslogtreecommitdiff
path: root/urldecode.c
blob: fbd39b346377cc4569327a66ea3f24cc7e178345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* Copyright (C) 2015 Luke Shumaker <lukeshu@sbcglobal.net> */
#include <stdio.h>

/* ungetc is only guaranteed for 1 char; use our own buffer */
int buf[2];
int cnt = 0;
int ab = 0;
int _getchar() {
	if (cnt > 0)
		cnt--;
	else
		buf[ab] = getchar();
	int ret = buf[ab];
	ab = !ab;
	return ret;
}
void _ungetchar() {
	cnt++;
	ab = !ab;
}

int hex(int c) {
	if ('0' <= c && c <= '9')
		return c - '0';
	if ('A' <= c && c <= 'F')
		return 10 + c - 'A';
	if ('a' <= c && c <= 'f')
		return 10 + c - 'a';
	return -1;
}

int
main () {
	int c, v1, v2;
	while ((c = _getchar()) != EOF) {
		switch (c) {
		case '%':
			if ((v1 = hex(_getchar())) < 0) {
				putchar('%');
				_ungetchar();
				continue;
			}
			if ((v2 = hex(_getchar())) < 0) {
				putchar('%');
				_ungetchar();
				_ungetchar();
				continue;
			}
			putchar(((v1 << 4) & 0xF0) | (v2 & 0x0F));
			break;
		case '+':
			putchar(' ');
			break;
		default:
			putchar(c);
			break;
		}
	}
	return 0;
}