optimize printing the index of an array with the -n option - json2tsv - JSON to… | |
git clone git://git.codemadness.org/json2tsv | |
Log | |
Files | |
Refs | |
README | |
LICENSE | |
--- | |
commit 7c6507b10767029b3d4585e3e65d231f66fa904b | |
parent 18215ba6f1a9f2c76ffceded0670eb2b2f466792 | |
Author: Hiltjo Posthuma <[email protected]> | |
Date: Fri, 24 Sep 2021 14:27:38 +0200 | |
optimize printing the index of an array with the -n option | |
Diffstat: | |
M json2tsv.c | 35 +++++++++++++++++++++++++----… | |
1 file changed, 29 insertions(+), 6 deletions(-) | |
--- | |
diff --git a/json2tsv.c b/json2tsv.c | |
@@ -1,5 +1,7 @@ | |
#include <ctype.h> | |
#include <errno.h> | |
+#include <limits.h> | |
+#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
@@ -48,6 +50,29 @@ rs_printvalue(const char *s) | |
} | |
} | |
+/* optimized printing an unsigned number (compared to printf("%zu"); */ | |
+void | |
+printnum(uintmax_t x) | |
+{ | |
+ char buf[64], *s, *e; | |
+ unsigned long y; | |
+ | |
+ if (!x) { | |
+ putchar('0'); | |
+ return; | |
+ } | |
+ | |
+ s = e = buf + sizeof(buf) - 1; | |
+ | |
+ for (; x > ULONG_MAX; x /= 10) | |
+ *--s = '0' + x % 10; | |
+ for (y = x; y; y /= 10) | |
+ *--s = '0' + y % 10; | |
+ | |
+ for (; s < e; s++) | |
+ putchar(*s); | |
+} | |
+ | |
void | |
processnode(struct json_node *nodes, size_t depth, const char *value) | |
{ | |
@@ -64,12 +89,10 @@ processnode(struct json_node *nodes, size_t depth, const ch… | |
if (nodes[i].type == JSON_TYPE_OBJECT) { | |
putchar('.'); | |
} else if (nodes[i].type == JSON_TYPE_ARRAY) { | |
- if (nflag) { | |
- printf("[%zu]", nodes[i].index); | |
- } else { | |
- putchar('['); | |
- putchar(']'); | |
- } | |
+ putchar('['); | |
+ if (nflag) | |
+ printnum(nodes[i].index); | |
+ putchar(']'); | |
} | |
} | |