From f5d0d2d35396e46c4e0431d28c6895396f971d20 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Mon, 4 May 2015 17:30:19 -0400 Subject: Rewrite urldecode in C --- urldecode.c | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ urldecode.php | 6 ------ 2 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 urldecode.c delete mode 100644 urldecode.php diff --git a/urldecode.c b/urldecode.c new file mode 100644 index 0000000..fbd39b3 --- /dev/null +++ b/urldecode.c @@ -0,0 +1,60 @@ +/* Copyright (C) 2015 Luke Shumaker */ +#include + +/* 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; +} diff --git a/urldecode.php b/urldecode.php deleted file mode 100644 index 5d88b9b..0000000 --- a/urldecode.php +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/php -n - - -$contents = file_get_contents('php://stdin'); -echo urldecode($contents); -- cgit v1.2.3-2-g168b