/* Control characters out of JSON text (stripctl.h), for what a provider's web search brings from the
* open web into the transcript: a header-only function so each stream decoder, which is built and
* tested on its own, carries it. */
#ifndef PIC_STRIPCTL_H
#define PIC_STRIPCTL_H
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/* Whether code point CP could steer a terminal or reorder text when shown: C0 (but newline and tab),
* DEL, C1, and the bidi controls U+061C, U+200E, U+200F, U+202A-202E and U+2066-2069 (the rule the
* names of paired phones follow, remote.c). */
static inline int pic_cp_steers(unsigned long cp) {
return (cp < 0x20 && cp != 0x0a && cp != 0x09) || (cp >= 0x7f && cp <= 0x9f) || cp == 0x061c || cp == 0x200e ||
cp == 0x200f || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069);
}
/* Removes from the JSON text J (in place) every character that PIC_CP_STEERS says, as the text
* decodes: an escape counts for what it stands for, so \r, \b, \f and \u000d go as \u001b does, and
* only \n and \t stay of the controls; raw bytes of the same characters in UTF-8 go too. An escaped
* backslash or quote is skipped whole, so \\u001b stays the text it is. */
static inline void pic_json_strip_controls(char *j) {
char *o = j;
for (const char *p = j; *p;) {
unsigned char c = (unsigned char)*p;
if (c == '\\' && p[1] == 'u' && isxdigit((unsigned char)p[2]) && isxdigit((unsigned char)p[3]) &&
isxdigit((unsigned char)p[4]) && isxdigit((unsigned char)p[5])) {
char hx[5] = {p[2], p[3], p[4], p[5], 0};
if (pic_cp_steers(strtoul(hx, NULL, 16))) {
p += 6;
continue;
}
memmove(o, p, 6);
o += 6;
p += 6;
} else if (c == '\\' && p[1]) {
if (p[1] != 'r' && p[1] != 'b' && p[1] != 'f') { /* \n, \t, \", \\, \/ stay; the other short forms are controls */
o[0] = p[0];
o[1] = p[1];
o += 2;
}
p += 2;
} else if (c < 0x80) {
if (!pic_cp_steers(c)) {
*o++ = *p;
}
p++;
} else if ((c & 0xe0) == 0xc0 && ((unsigned char)p[1] & 0xc0) == 0x80) {
if (!pic_cp_steers(((unsigned long)(c & 0x1f) << 6) | ((unsigned char)p[1] & 0x3f))) {
*o++ = p[0];
*o++ = p[1];
}
p += 2;
} else if ((c & 0xf0) == 0xe0 && ((unsigned char)p[1] & 0xc0) == 0x80 && ((unsigned char)p[2] & 0xc0) == 0x80) {
if (!pic_cp_steers(((unsigned long)(c & 0x0f) << 12) | ((unsigned long)((unsigned char)p[1] & 0x3f) << 6) |
((unsigned char)p[2] & 0x3f))) {
memmove(o, p, 3);
o += 3;
}
p += 3;
} else {
*o++ = *p++;
}
}
*o = '\0';
}
#endif