diff options
Diffstat (limited to 'src/lib/common.c')
-rw-r--r-- | src/lib/common.c | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/lib/common.c b/src/lib/common.c index 111366782..44ff2ab98 100644 --- a/src/lib/common.c +++ b/src/lib/common.c | |||
@@ -404,6 +404,64 @@ char *replace_cntrl_chars(const char *str, char c) { | |||
404 | return rv; | 404 | return rv; |
405 | } | 405 | } |
406 | 406 | ||
407 | // Replaces each control character in str with an escape sequence, such as by | ||
408 | // replacing '\n' (0x0a) with "\\n" (0x5c6e). | ||
409 | char *escape_cntrl_chars(const char *str) { | ||
410 | if (str == NULL) | ||
411 | return NULL; | ||
412 | |||
413 | unsigned int cntrl_chars = 0; | ||
414 | const char *c = str; | ||
415 | while (*c) { | ||
416 | switch (*c++) { | ||
417 | case '\b': | ||
418 | case '\a': | ||
419 | case '\e': | ||
420 | case '\f': | ||
421 | case '\n': | ||
422 | case '\r': | ||
423 | case '\t': | ||
424 | case '\v': | ||
425 | case '\"': | ||
426 | case '\'': | ||
427 | case '\?': | ||
428 | case '\\': | ||
429 | ++cntrl_chars; | ||
430 | default: | ||
431 | break; | ||
432 | } | ||
433 | } | ||
434 | char *ptr, *rv = malloc(strlen(str) + cntrl_chars + 1); | ||
435 | if (!rv) | ||
436 | errExit("malloc"); | ||
437 | ptr = rv; | ||
438 | c = str; | ||
439 | while (*c) { | ||
440 | if (iscntrl(*c)) { | ||
441 | *ptr++ = '\\'; | ||
442 | switch (*c) { | ||
443 | case '\b': *ptr++ = 'b'; break; | ||
444 | case '\a': *ptr++ = 'a'; break; | ||
445 | case '\e': *ptr++ = 'e'; break; | ||
446 | case '\f': *ptr++ = 'f'; break; | ||
447 | case '\n': *ptr++ = 'n'; break; | ||
448 | case '\r': *ptr++ = 'r'; break; | ||
449 | case '\t': *ptr++ = 't'; break; | ||
450 | case '\v': *ptr++ = 'v'; break; | ||
451 | case '\"': *ptr++ = '\"'; break; | ||
452 | case '\'': *ptr++ = '\''; break; | ||
453 | case '\?': *ptr++ = '?'; break; | ||
454 | case '\\': *ptr++ = '\\'; break; | ||
455 | } | ||
456 | } else { | ||
457 | *ptr++ = *c; | ||
458 | } | ||
459 | c++; | ||
460 | } | ||
461 | *ptr = '\0'; | ||
462 | return rv; | ||
463 | } | ||
464 | |||
407 | int has_cntrl_chars(const char *str) { | 465 | int has_cntrl_chars(const char *str) { |
408 | assert(str); | 466 | assert(str); |
409 | 467 | ||