From ea2afe3afb9f8798f5bf5bee4300c6a6280342c3 Mon Sep 17 00:00:00 2001 From: Alex 'AdUser' Z Date: Sun, 18 Sep 2011 19:50:54 +1100 Subject: [PATCH] + added handlers for integer/string objects and some yajl init functions --- src/torrent2json.c | 79 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/src/torrent2json.c b/src/torrent2json.c index c393f82..dbafe96 100644 --- a/src/torrent2json.c +++ b/src/torrent2json.c @@ -14,9 +14,72 @@ FILE *in; FILE *out; -void (*handler)(void); +struct yajl_gen_t *gen = NULL; -void (*select_handler(char chr))(void) +/* object handler prototype */ +void (*handler)(char); + +void +get_integer(char chr) +{ /* 'chr' always 'i' in this case */ + int c = '\0'; + bool cont = true; + long int value = 0; /* signed */ + + while (cont) + { + if (!cont) break; + + c = fgetc(in); + switch ((isdigit(c) != 0) ? '0' : c) /* little hack here */ + { + case '0' : + value *= 10; /* (0 * 10) -> 0, so it works correct */ + value += c - '0'; + break; + case '-' : + value *= -1; + break; + case 'e' : /* integer end marker */ + default : /* or garbled data */ + cont = false; + break; + } + } + + yajl_gen_integer(gen, value); +} + +void +get_string(char chr) +{ + /* in this case 'chr' first digit of string lenght */ + unsigned int len = (unsigned char) chr - '0'; + int c = '\0'; + int i = 0; + unsigned char *buf = NULL; + + /* first, get string lenght */ + while (isdigit((c = fgetc(in)))) + len *= 10, len += c - '0'; + /* 'c' now should contain ':' */ + + if ((buf = malloc(sizeof(char) * len + 1)) == NULL) + { + fprintf(stderr, "Can't allocate memory, exiting.\n"); + exit(EXIT_FAILURE); + } + + memset(buf, '\0', len + 1); + for (i = 0; i <= len; i++) + *(buf + i * sizeof(char)) = fgetc(in); + + yajl_gen_string(gen, buf, len); + + free(buf); +} + +void (*select_handler(char chr))(char) { handler = NULL; @@ -44,16 +107,26 @@ int main(int argc, char **argv) { int chr = '\0'; + const unsigned char *buf = NULL; + size_t len = 0; in = stdin; out = stdout; + gen = yajl_gen_alloc(NULL); + yajl_gen_config(gen, yajl_gen_beautify, 1); + yajl_gen_config(gen, yajl_gen_indent_string, " "); + while ((chr = fgetc(in)) != EOF); { handler = select_handler(chr); - handler(); + handler(chr); } + yajl_gen_get_buf(gen, &buf, &len); + fprintf(out, "%s", buf); + yajl_gen_free(gen); + exit(EXIT_SUCCESS); }