MCPcopy Create free account
hub / github.com/armink/struct2json / print_string_ptr

Function print_string_ptr

struct2json/src/cJSON.c:253–308  ·  view source on GitHub ↗

Render the cstring provided to an escaped version that can be printed. */

Source from the content-addressed store, hash-verified

251
252/* Render the cstring provided to an escaped version that can be printed. */
253static char *print_string_ptr(const char *str,printbuffer *p)
254{
255 const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token;
256
257 for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0;
258 if (!flag)
259 {
260 len=ptr-str;
261 if (p) out=ensure(p,len+3);
262 else out=(char*)cJSON_malloc(len+3);
263 if (!out) return 0;
264 ptr2=out;*ptr2++='\"';
265 strcpy(ptr2,str);
266 ptr2[len]='\"';
267 ptr2[len+1]=0;
268 return out;
269 }
270
271 if (!str)
272 {
273 if (p) out=ensure(p,3);
274 else out=(char*)cJSON_malloc(3);
275 if (!out) return 0;
276 strcpy(out,"\"\"");
277 return out;
278 }
279 ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
280
281 if (p) out=ensure(p,len+3);
282 else out=(char*)cJSON_malloc(len+3);
283 if (!out) return 0;
284
285 ptr2=out;ptr=str;
286 *ptr2++='\"';
287 while (*ptr)
288 {
289 if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
290 else
291 {
292 *ptr2++='\\';
293 switch (token=*ptr++)
294 {
295 case '\\': *ptr2++='\\'; break;
296 case '\"': *ptr2++='\"'; break;
297 case '\b': *ptr2++='b'; break;
298 case '\f': *ptr2++='f'; break;
299 case '\n': *ptr2++='n'; break;
300 case '\r': *ptr2++='r'; break;
301 case '\t': *ptr2++='t'; break;
302 default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */
303 }
304 }
305 }
306 *ptr2++='\"';*ptr2++=0;
307 return out;
308}
309/* Invote print_string_ptr (which is useful) on an item. */
310static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);}

Callers 2

print_stringFunction · 0.85
print_objectFunction · 0.85

Calls 1

ensureFunction · 0.85

Tested by

no test coverage detected