Line data Source code
1 : /* Copyright 2025 G. Branden Robinson 2 : 3 : This file is part of groff, the GNU roff typesetting system. 4 : 5 : groff is free software; you can redistribute it and/or modify it under 6 : the terms of the GNU General Public License as published by the Free 7 : Software Foundation, either version 3 of the License, or 8 : (at your option) any later version. 9 : 10 : groff is distributed in the hope that it will be useful, but WITHOUT ANY 11 : WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 : for more details. 14 : 15 : You should have received a copy of the GNU General Public License 16 : along with this program. If not, see <http://www.gnu.org/licenses/>. */ 17 : 18 : #ifdef HAVE_CONFIG_H 19 : #include <config.h> 20 : #endif 21 : 22 : #include <stdio.h> // snprintf() 23 : 24 : #include "cset.h" // csprint() 25 : #include "json-encode.h" // json_char 26 : 27 : // Return JSON representation of character `c` without bracketing `"`s. 28 6 : json_char json_encode_char(unsigned char c) 29 : { 30 : json_char jc; 31 : // These printable characters require escaping. 32 6 : if (('"' == c) || ('\\' == c) || ('/' == c)) { 33 0 : jc.len = 2; 34 0 : jc.buf[0] = '\\'; 35 0 : jc.buf[1] = c; 36 : } 37 6 : else if (csprint(c)) { 38 6 : jc.len = 1; 39 6 : jc.buf[0] = c; 40 : } 41 0 : else if ('\b' == c) { 42 0 : jc.len = 2; 43 0 : jc.buf[0] = '\\'; 44 0 : jc.buf[1] = 'b'; 45 : } 46 0 : else if ('\t' == c) { 47 0 : jc.len = 2; 48 0 : jc.buf[0] = '\\'; 49 0 : jc.buf[1] = 't'; 50 : } 51 0 : else if ('\n' == c) { 52 0 : jc.len = 2; 53 0 : jc.buf[0] = '\\'; 54 0 : jc.buf[1] = 'n'; 55 : } 56 0 : else if ('\f' == c) { 57 0 : jc.len = 2; 58 0 : jc.buf[0] = '\\'; 59 0 : jc.buf[1] = 'f'; 60 : } 61 0 : else if ('\r' == c) { 62 0 : jc.len = 2; 63 0 : jc.buf[0] = '\\'; 64 0 : jc.buf[1] = 'r'; 65 : } 66 : else { 67 0 : jc.len = 6; 68 0 : (void) snprintf(jc.buf, sizeof jc.buf, "\\u%04X", c); 69 : } 70 6 : return jc; 71 : } 72 : 73 : // Local Variables: 74 : // fill-column: 72 75 : // mode: C++ 76 : // End: 77 : // vim: set cindent noexpandtab shiftwidth=2 textwidth=72: