1 /*
2 * Make a hexdump copy of C string
3 *
4 * Copyright (c) 2016-2021 Dmitry V. Levin <ldv@strace.io>
5 * All rights reserved.
6 *
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
9
10 #include "tests.h"
11
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <string.h>
15
16 const char *
17 hexdump_memdup(const char *src, size_t len)
18 {
19 size_t dst_size = 3 * len + 2;
20 assert(dst_size > len);
21
22 char *dst = malloc(dst_size);
23 if (!dst)
24 perror_msg_and_fail("malloc(%zu)", dst_size);
25
26 char *p = dst;
27 const unsigned char *usrc = (const unsigned char *) src;
28 for (size_t i = 0; i < len; ++i) {
29 unsigned int c = usrc[i];
30 *(p++) = ' ';
31 if (i == 8)
32 *(p++) = ' ';
33 *(p++) = "0123456789abcdef"[c >> 4];
34 *(p++) = "0123456789abcdef"[c & 0xf];
35 }
36 *p = '\0';
37
38 return dst;
39 }
40
41 const char *
42 hexdump_strdup(const char *src)
43 {
44 return hexdump_memdup(src, strlen(src));
45 }