]> Pileus Git - ~andy/fetchmail/blob - sdump.c
Credit John Beck's fixes.
[~andy/fetchmail] / sdump.c
1 /* sdump.c -- library to allocate and format a printable version of a
2  * string with embedded NUL */
3
4 /** \file sdump.c
5  * \author Matthias Andree
6  * \date 2009
7  *
8  * This file is available under the GNU Lesser General Public License
9  * v2.1 or any later version of the GNU LGPL.
10  */
11
12 #include <ctype.h>  /* for isprint() */
13 #include <stdio.h>  /* for sprintf() */
14 #include <stdlib.h> /* for size_t */
15 #include "xmalloc.h" /* for xmalloc() */
16
17 #include "sdump.h"   /* for prototype */
18
19 /** sdump converts a byte string \a in of size \a len into a printable
20  * string and returns a pointer to the memory region.
21  * \returns a pointer to a xmalloc()ed string that the caller must
22  * free() after use. This function causes program abort on failure
23  * through xmalloc. xmalloc is a function that calls malloc() and aborts
24  * the program if malloc() returned NULL i. e. failure. */
25 char *sdump(const char *in, size_t len)
26 {
27     size_t outlen = 0, i;
28     char *out, *oi;
29
30     for (i = 0; i < len; i++) {
31         outlen += isprint((unsigned char)in[i]) ? 1 : 4;
32     }
33
34     oi = out = (char *)xmalloc(outlen + 1);
35     for (i = 0; i < len; i++) {
36         if (isprint((unsigned char)in[i])) {
37             *(oi++) = in[i];
38         } else {
39             oi += sprintf(oi, "\\x%02X", (unsigned char)in[i]);
40         }
41     }
42     *oi = '\0';
43     return out;
44 }