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