]> Pileus Git - ~andy/fetchmail/blob - sdump.c
5782f134b67eaa7d9a5be553616ab6d3efb602af
[~andy/fetchmail] / sdump.c
1 /* sdump.c -- library to allocate a printable version of a string */
2 /** \file sdump.c
3  * \author Matthias Andree
4  * \date 2009
5  */
6
7 #include <ctype.h>  /* for isprint() */
8 #include <stdio.h>  /* for sprintf() */
9 #include <stdlib.h> /* for size_t */
10 #include "xmalloc.h" /* for xmalloc() */
11
12 #include "sdump.h"   /* for prototype */
13
14 /** sdump converts a byte string \a in of size \a len into a printable
15  * string and returns a pointer to the memory region.
16  * \returns a pointer to a xmalloc()ed string that the caller must
17  * free() after use. This function causes program abort on failure. */
18 char *sdump(const char *in, size_t len)
19 {
20     size_t outlen = 0, i;
21     char *out, *oi;
22
23     for (i = 0; i < len; i++) {
24         outlen += isprint((unsigned char)in[i]) ? 1 : 4;
25     }
26
27     oi = out = (char *)xmalloc(outlen + 1);
28     for (i = 0; i < len; i++) {
29         if (isprint((unsigned char)in[i])) {
30             *(oi++) = in[i];
31         } else {
32             oi += sprintf(oi, "\\x%02X", in[i]);
33         }
34     }
35     *oi = '\0';
36     return out;
37 }