summaryrefslogtreecommitdiffstats
path: root/utils/bencoding.c
diff options
context:
space:
mode:
authorAnton Luka Šijanec <anton@sijanec.eu>2022-11-21 20:11:12 +0100
committerAnton Luka Šijanec <anton@sijanec.eu>2022-11-21 20:11:12 +0100
commit8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb (patch)
tree27508c3ffa05f5934bd7af60c34736d89e0e5954 /utils/bencoding.c
parentinitial commit, UNTESTED bencoding parser (diff)
downloadtravnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.tar
travnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.tar.gz
travnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.tar.bz2
travnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.tar.lz
travnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.tar.xz
travnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.tar.zst
travnik-8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb.zip
Diffstat (limited to 'utils/bencoding.c')
-rw-r--r--utils/bencoding.c36
1 files changed, 36 insertions, 0 deletions
diff --git a/utils/bencoding.c b/utils/bencoding.c
new file mode 100644
index 0000000..a60e1b3
--- /dev/null
+++ b/utils/bencoding.c
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <error.h>
+#include <signal.h>
+#include <cjson/cJSON.h>
+#include <bencoding.c>
+#define S0(x) (x ? x : "")
+int main (int argc, char ** argv) {
+ if (argc != 1+1)
+ error_at_line(1, 0, __FILE__, __LINE__, "%s encode < json || %s decode < bencoding", S0(argv[0]), S0(argv[0]));
+ int size = 2048;
+ int len = 0;
+ char * in = malloc(size);
+ while (!feof(stdin) && !ferror(stdin)) {
+ if (!in)
+ error_at_line(2, 0, __FILE__, __LINE__, "heap alloc failed");
+ len += fread(in, 1, size-len-1, stdin);
+ if ((size - len) < 1024)
+ in = realloc(in, size *= 2);
+ }
+ if (argv[1][0] == 'e')
+ error_at_line(3, 0, __FILE__, __LINE__, "N/I");
+ struct bencoding * bencoding = bdecode(in, size, terminate);
+ len = b2json_length(bencoding);
+ char out[len+1];
+ char * end = b2json(out, bencoding);
+ *end = '\0';
+ puts(out);
+ if (end - out != len)
+ error_at_line(4, 0, __FILE__, __LINE__, "b2json wrote %ld instead of %d bytes.", end-out, len);
+ fprintf(stderr, "len: %d\n", len);
+ free_bencoding(bencoding);
+ free(in);
+ return 0;
+}