http_dec.c
author viric@llimona
Sun, 02 Sep 2007 15:59:31 +0200
changeset 26 700a68421116
parent 19 4da6dbf01423
permissions -rw-r--r--
Adding .hgignore and the ia5test.

#include <stdio.h>
#include <unicode/utf8.h>
#include "dictre.h"

static int url_get(FILE *f)
{
    int val;

    val = fgetc(f);
    if (val == '%')
    {
        unsigned char num[3];
        num[2] = '\0';
        num[0] = fgetc(f);
        num[1] = fgetc(f);
        val = strtol(num, 0, 16);
    } else if (val == '&')
        return END_OF_URL;
    else if (val == '+')
        return ' ';
    /*printf("[%i]", val);*/
    return val;
}

static int char2num(unsigned char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    if (c >= 'A' && c <= 'Z')
        return c + 10 - 'A';
    if (c >= 'a' && c <= 'z')
        return c + 10 - 'a';
    return 0;
}

int http_getc(FILE *f)
{
    int c;
    static unsigned char tmp[6]; /* for a UTF-8 string */
    static int itmp = -1;
    static int tmplen;

    if (itmp == -1)
    {
        c = url_get(f);
        if (c == '&')
        {
            c = url_get(f);
            if (c == '#')
            {
                char iserror = 0;
                int entval;
                /*Get number*/
                entval = 0;
                while((c = url_get(f)) != ';')
                {
                    /* Digits in base 10 */
                    entval = char2num(c) + entval * 10;
                }
                /*printf("{%i}", entval);*/
                /*Get utf-8 version*/
                tmplen = 0;
                U8_APPEND(tmp, tmplen, 6, entval, iserror);
                if (iserror)
                    return -3;
                /* We need not to program itmp for the next run
                 * if we have only one character to send */
                if (tmplen != 1)
                    itmp = 1;
                return tmp[0];
            }
            else
                return HTTP_DECODE_ERROR; /* ERROR! */
        }
    } else /* We already have a character to keep on sending */
    {
        int tosend;
        tosend = itmp;
        ++itmp;
        if (itmp == tmplen)
            itmp = -1;
        return tmp[tosend];
    }
    return c;
}