json_encode_str.c: some optimizations and cleanup - randomcrap - random crap programs of varying quality
(HTM) git clone git://git.codemadness.org/randomcrap
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 07527edd14eaf6f5a1f2356d80da9c7e1e7b5bda
(DIR) parent 836d5914004bba2b59ec8f6813738c8823009111
(HTM) Author: Hiltjo Posthuma <hiltjo@codemadness.org>
Date: Sun, 10 Aug 2025 19:25:38 +0200
json_encode_str.c: some optimizations and cleanup
... because why not.
Diffstat:
M json_encode_str.c | 49 ++++++++++++++-----------------
1 file changed, 22 insertions(+), 27 deletions(-)
---
(DIR) diff --git a/json_encode_str.c b/json_encode_str.c
@@ -2,6 +2,9 @@
#include <stdio.h>
+#define GETCHAR getchar_unlocked
+#define PUTCHAR putchar_unlocked
+
static int
digit2hex(int c)
{
@@ -17,39 +20,31 @@ main(void)
{
int c;
- putchar('"');
-
- while ((c = getchar()) != EOF) {
- switch (c) {
- case '"':
- case '\\':
- putchar('\\');
- putchar(c);
- continue;
- }
-
+ PUTCHAR('"');
+ while ((c = GETCHAR()) != EOF) {
switch (c) {
- case '\b': putchar('\\'); putchar('b'); continue;
- case '\f': putchar('\\'); putchar('f'); continue;
- case '\n': putchar('\\'); putchar('n'); continue;
- case '\r': putchar('\\'); putchar('r'); continue;
- case '\t': putchar('\\'); putchar('t'); continue;
- default:
+ case '"': PUTCHAR('\\'); putchar('"'); break;
+ case '\\': PUTCHAR('\\'); PUTCHAR('\\'); break;
+ case '\b': PUTCHAR('\\'); PUTCHAR('b'); break;
+ case '\f': PUTCHAR('\\'); PUTCHAR('f'); break;
+ case '\n': PUTCHAR('\\'); PUTCHAR('n'); break;
+ case '\r': PUTCHAR('\\'); PUTCHAR('r'); break;
+ case '\t': PUTCHAR('\\'); PUTCHAR('t'); break;
+ default: /* control character */
if (c < 0x20) {
- putchar('\\');
- putchar('u');
- putchar('0');
- putchar('0');
- putchar(digit2hex((c >> 4)));
- putchar(digit2hex(c & 0x0f));
- continue;
+ PUTCHAR('\\');
+ PUTCHAR('u');
+ PUTCHAR('0');
+ PUTCHAR('0');
+ PUTCHAR(digit2hex((c >> 4)));
+ PUTCHAR(digit2hex(c & 0x0f));
+ } else {
+ PUTCHAR(c);
}
break;
}
- putchar(c);
}
-
- putchar('"');
+ PUTCHAR('"');
if (ferror(stdin) || fflush(stdout) || ferror(stdout)) {
perror(NULL);