Skip to content
pi-c Artifact [145c2d94c2]
Login

Artifact [145c2d94c2]

Artifact 145c2d94c28a60c6054bba63001dcafa75c1107e1ab4500f148b7cd59d9b7b9e:


/* 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>

/* Removes from the JSON text J (in place) what could steer a terminal when shown: the escapes
 * \u0000-\u001f (the short forms for newline and tab are not those), \u007f and \u0080-\u009f, and
 * the raw bytes DEL and C1 as UTF-8. An escaped backslash is skipped whole, so \\u001b stays text. */
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' && p[2] == '0' && p[3] == '0' && isxdigit((unsigned char)p[4]) && isxdigit((unsigned char)p[5])) {
            char hx[3] = {p[4], p[5], 0};
            int v = (int)strtol(hx, NULL, 16);
            if (v < 0x20 || (v >= 0x7f && v <= 0x9f)) {
                p += 6;
                continue;
            }
            memmove(o, p, 6);
            o += 6;
            p += 6;
        } else if (c == '\\' && p[1]) { /* an escape: the pair stays whole, so \\u001b is a backslash and text */
            o[0] = p[0];
            o[1] = p[1];
            o += 2;
            p += 2;
        } else if (c == 0x7f || (c == 0xc2 && (unsigned char)p[1] >= 0x80 && (unsigned char)p[1] <= 0x9f)) {
            p += c == 0x7f ? 1 : 2;
        } else {
            *o++ = *p++;
        }
    }
    *o = '\0';
}

#endif